import OtpModel from '../models/Otp';
import { EmailService } from './EmailService';
import { humanizeClientError } from './humanReadableError';

export class OtpUtils {
  // Generate a 6-digit OTP
  public static generateOtp(): string {
    return Math.floor(100000 + Math.random() * 900000).toString();
  }

  // Create and save OTP for user (using upsert to maintain single document per user per type)
  public static async createOtp(
    userId: string,
    type: 'signup' | 'forgot-password' | 'resend-otp' = 'signup'
  ): Promise<{ success: boolean; otp?: string; message: string }> {
    try {
      // Generate new OTP
      const otp = this.generateOtp();

      // Use findOneAndUpdate with upsert to maintain single OTP document per user per type
      await OtpModel.findOneAndUpdate(
        { userId, type },
        {
          otp,
          isUsed: false,
          type,
          expiresAt: new Date(Date.now() + 10 * 60 * 1000), // 10 minutes from now
          updatedAt: new Date(),
        },
        {
          upsert: true, // Create if doesn't exist, update if exists
          new: true,
          setDefaultsOnInsert: true,
        }
      );

      return {
        success: true,
        otp,
        message: 'OTP generated successfully',
      };
    } catch (error: any) {
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not generate a verification code. Please try again.'
        ),
      };
    }
  }

  // Verify OTP
  public static async verifyOtp(
    userId: string,
    otp: string,
    type: 'signup' | 'forgot-password' = 'signup'
  ): Promise<{ success: boolean; message: string }> {
    try {
      // Find valid OTP for user with specific type
      const otpRecord = await OtpModel.findOne({
        userId,
        otp,
        type,
        isUsed: false,
        expiresAt: { $gt: new Date() },
      });

      if (!otpRecord) {
        return {
          success: false,
          message: 'Invalid or expired OTP',
        };
      }

      // Mark OTP as used
      otpRecord.isUsed = true;
      await otpRecord.save();

      return {
        success: true,
        message: 'OTP verified successfully',
      };
    } catch (error: any) {
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not verify that code. Please try again.'
        ),
      };
    }
  }

  // Send OTP via email with beautiful template
  public static async sendOtp(
    email: string,
    otp: string,
    recipientName?: string
  ): Promise<{ success: boolean; message: string }> {
    try {
      // Send OTP email using EmailService
      const emailServiceInstance = new EmailService();
      const emailResult = await emailServiceInstance.sendOtpEmail(
        email,
        otp,
        recipientName
      );

      if (!emailResult.success) {
        // Fallback: log OTP if email fails (development only)
        if (process.env.NODE_ENV === 'development') {
          console.log(`Email failed, OTP for ${email}: ${otp}`);
        }
        return emailResult;
      }

      return {
        success: true,
        message: 'OTP sent successfully to your email',
      };
    } catch (error: any) {
      // Fallback: log OTP if email fails (development only)
      if (process.env.NODE_ENV === 'development') {
        console.log(`Email error, OTP for ${email}: ${otp}`);
      }

      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not send the verification code. Please try again.'
        ),
      };
    }
  }

  // Enhanced method to create and send OTP in one call
  public static async createAndSendOtp(
    userId: string,
    email: string,
    recipientName?: string,
    type: 'signup' | 'forgot-password' | 'resend-otp' = 'signup'
  ): Promise<{ success: boolean; message: string }> {
    try {
      // Create OTP
      const otpResult = await this.createOtp(userId, type);

      if (!otpResult.success || !otpResult.otp) {
        return otpResult;
      }

      // Send OTP via email
      const sendResult = await this.sendOtp(email, otpResult.otp, recipientName);

      return sendResult;
    } catch (error: any) {
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not create or send the verification code. Please try again.'
        ),
      };
    }
  }
}
