import { getDb } from "../db.ts";
import { users } from "../../drizzle/schema.ts";
import { eq } from "drizzle-orm";
import crypto from "crypto";

// Simple TOTP implementation (in production, use speakeasy or similar)
export class TwoFactorAuthService {
  /**
   * Generate a TOTP secret and QR code
   */
  static async generateSecret(userId: number) {
    // Generate a random secret (base32 encoded)
    const secret = crypto.randomBytes(20).toString("base64");
    
    // Create QR code data (simplified - in production use qrcode library)
    const qrCodeData = `otpauth://totp/CoinKrazy:user${userId}?secret=${secret}&issuer=CoinKrazy`;
    
    return {
      secret,
      qrCodeUrl: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrCodeData)}`,
      qrCode: qrCodeData,
    };
  }

  /**
   * Verify a TOTP code
   */
  static verifyCode(secret: string, code: string): boolean {
    // Simplified verification - in production use speakeasy
    // This is a placeholder that accepts the code if it matches a pattern
    if (!code || code.length !== 6 || !/^\d+$/.test(code)) {
      return false;
    }

    // In production, use speakeasy.totp.verify()
    // For now, we'll accept any valid 6-digit code as a placeholder
    return true;
  }

  /**
   * Enable 2FA for a user
   */
  static async enable2FA(userId: number, secret: string) {
    const db = await getDb();
    if (!db) throw new Error("Database unavailable");
    await db
      .update(users)
      .set({
        twoFactorEnabled: 1,
        twoFactorSecret: secret,
      })
      .where(eq(users.id, userId));

    return { success: true };
  }

  /**
   * Disable 2FA for a user
   */
  static async disable2FA(userId: number) {
    const db = await getDb();
    if (!db) throw new Error("Database unavailable");
    await db
      .update(users)
      .set({
        twoFactorEnabled: 0,
        twoFactorSecret: null,
      })
      .where(eq(users.id, userId));

    return { success: true };
  }

  /**
   * Check if user has 2FA enabled
   */
  static async is2FAEnabled(userId: number): Promise<boolean> {
    const db = await getDb();
    if (!db) return false;
    const result = await db.select({ twoFactorEnabled: users.twoFactorEnabled })
      .from(users)
      .where(eq(users.id, userId))
      .limit(1);
    return result[0]?.twoFactorEnabled === 1;
  }

  /**
   * Get 2FA secret for a user
   */
  static async getSecret(userId: number): Promise<string | null> {
    const db = await getDb();
    if (!db) return null;
    const result = await db.select({ twoFactorSecret: users.twoFactorSecret })
      .from(users)
      .where(eq(users.id, userId))
      .limit(1);
    return result[0]?.twoFactorSecret || null;
  }
}
