import { Pool, PoolClient } from 'pg';
import type { UserLicense } from '../types/user.js';
import { UserLicenseSchema } from '../types/user.js';

export class UserService {
  private pool: Pool;

  constructor(connectionString: string) {
    this.pool = new Pool({
      connectionString,
      max: 20,
      idleTimeoutMillis: 30000,
      connectionTimeoutMillis: 2000,
    });
  }

  /**
   * Get user license by user ID
   */
  async getUserLicense(userId: string): Promise<UserLicense | null> {
    const client = await this.pool.connect();
    try {
      const result = await client.query(
        `SELECT
          user_id as "userId",
          email,
          license_type as "licenseType",
          features,
          resource_limits as "resourceLimits",
          mcp_server_url as "mcpServerUrl",
          preferred_model as "preferredModel",
          expires_at as "expiresAt",
          created_at as "createdAt",
          updated_at as "updatedAt"
        FROM user_licenses
        WHERE user_id = $1
          AND (expires_at IS NULL OR expires_at > NOW())`,
        [userId]
      );

      if (result.rows.length === 0) {
        return null;
      }

      const row = result.rows[0];

      // Parse and validate
      return UserLicenseSchema.parse({
        userId: row.userId,
        email: row.email,
        licenseType: row.licenseType,
        features: row.features,
        resourceLimits: row.resourceLimits,
        mcpServerUrl: row.mcpServerUrl,
        preferredModel: row.preferredModel,
        expiresAt: row.expiresAt,
        createdAt: row.createdAt,
        updatedAt: row.updatedAt,
      });
    } finally {
      client.release();
    }
  }

  /**
   * Get user ID from channel-specific identifier
   */
  async getUserIdFromChannel(channelType: string, channelUserId: string): Promise<string | null> {
    const client = await this.pool.connect();
    try {
      const result = await client.query(
        `SELECT user_id
        FROM user_channel_links
        WHERE channel_type = $1 AND channel_user_id = $2`,
        [channelType, channelUserId]
      );

      return result.rows.length > 0 ? result.rows[0].user_id : null;
    } finally {
      client.release();
    }
  }

  /**
   * Verify JWT token from web client
   * TODO: Implement JWT verification with JWKS
   */
  async verifyWebToken(token: string): Promise<string | null> {
    // Placeholder - implement JWT verification
    // For now, decode without verification (INSECURE - FOR DEV ONLY)
    try {
      const payload = JSON.parse(
        Buffer.from(token.split('.')[1], 'base64').toString()
      );
      return payload.sub || null;
    } catch {
      return null;
    }
  }

  /**
   * Close database pool
   */
  async close(): Promise<void> {
    await this.pool.end();
  }
}
