import { authenticator } from 'otplib';
import QRCode from 'qrcode';
import { Context } from '../types/context';
import { GraphQLError } from 'graphql';

const issuer = 'Sankofa Phoenix';

export async function setup2FA(context: Context) {
  if (!context.user) {
    throw new GraphQLError('Authentication required', {
      extensions: { code: 'UNAUTHENTICATED' },
    });
  }

  const secret = authenticator.generateSecret();
  const serviceName = 'Sankofa Phoenix';
  const accountName = context.user.email;

  const otpAuthUrl = authenticator.keyuri(accountName, serviceName, secret);

  // Generate QR code
  const qrCodeUrl = await QRCode.toDataURL(otpAuthUrl);

  // Store secret temporarily (in production, store encrypted in database)
  // For now, return it - in production, store it securely and require verification before enabling

  return {
    secret,
    qrCodeUrl,
  };
}

export async function verify2FA(context: Context, code: string, secret: string) {
  if (!context.user) {
    throw new GraphQLError('Authentication required', {
      extensions: { code: 'UNAUTHENTICATED' },
    });
  }

  const isValid = authenticator.verify({ token: code, secret });

  return {
    valid: isValid,
    enabled: false, // Will be set to true after enable2FA
  };
}

export async function enable2FA(context: Context, code: string, secret: string) {
  if (!context.user) {
    throw new GraphQLError('Authentication required', {
      extensions: { code: 'UNAUTHENTICATED' },
    });
  }

  const isValid = authenticator.verify({ token: code, secret });

  if (!isValid) {
    throw new GraphQLError('Invalid verification code', {
      extensions: { code: 'VALIDATION_ERROR' },
    });
  }

  // In production, store encrypted secret in database
  // For now, just return success
  // await db.users.update(context.user.id, { twoFactorSecret: encrypt(secret), twoFactorEnabled: true });

  return true;
}

export async function disable2FA(context: Context) {
  if (!context.user) {
    throw new GraphQLError('Authentication required', {
      extensions: { code: 'UNAUTHENTICATED' },
    });
  }

  // In production, remove 2FA from database
  // await db.users.update(context.user.id, { twoFactorSecret: null, twoFactorEnabled: false });

  return true;
}

