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

/**
 * Migration script to clean up duplicate OTP records and ensure single OTP per user
 * Run this once after deploying the updated OTP model
 */
export class OtpMigration {
  public static async cleanupDuplicateOtps(): Promise<{
    success: boolean;
    message: string;
    cleaned?: number;
  }> {
    try {
      console.log('Starting OTP cleanup migration...');

      // Get all users with multiple OTP records
      const duplicateUsers = await OtpModel.aggregate([
        {
          $group: {
            _id: '$userId',
            count: { $sum: 1 },
            otps: { $push: '$$ROOT' },
          },
        },
        {
          $match: { count: { $gt: 1 } },
        },
      ]);

      let cleanedCount = 0;

      for (const userGroup of duplicateUsers) {
        const userId = userGroup._id;
        const otps = userGroup.otps;

        // Sort by createdAt descending to keep the most recent
        otps.sort(
          (a: any, b: any) =>
            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        );

        // Keep the most recent OTP, delete the rest
        const otpsToDelete = otps.slice(1);

        for (const otp of otpsToDelete) {
          await OtpModel.findByIdAndDelete(otp._id);
          cleanedCount++;
        }

        console.log(`Cleaned ${otpsToDelete.length} duplicate OTPs for user ${userId}`);
      }

      console.log(
        `OTP cleanup migration completed. Cleaned ${cleanedCount} duplicate records.`
      );

      return {
        success: true,
        message: `Migration completed successfully. Cleaned ${cleanedCount} duplicate OTP records.`,
        cleaned: cleanedCount,
      };
    } catch (error: any) {
      console.error('OTP cleanup migration failed:', error);
      return {
        success: false,
        message: humanizeClientError(
          error,
          'The OTP cleanup migration could not be completed. Please try again.'
        ),
      };
    }
  }

  /**
   * Create unique index on userId if it doesn't exist
   */
  public static async ensureUniqueIndex(): Promise<{
    success: boolean;
    message: string;
  }> {
    try {
      console.log('Ensuring unique index on userId...');

      // Check if index already exists
      const indexes = await OtpModel.collection.indexes();
      const hasUniqueUserIdIndex = indexes.some(
        (index: any) => index.key && index.key.userId === 1 && index.unique === true
      );

      if (!hasUniqueUserIdIndex) {
        await OtpModel.collection.createIndex({ userId: 1 }, { unique: true });
        console.log('Unique index on userId created successfully');
      } else {
        console.log('Unique index on userId already exists');
      }

      return {
        success: true,
        message: 'Unique index ensured successfully',
      };
    } catch (error: any) {
      console.error('Failed to ensure unique index:', error);
      return {
        success: false,
        message: humanizeClientError(
          error,
          'We could not update the database index for OTP records. Please try again.'
        ),
      };
    }
  }

  /**
   * Run complete migration
   */
  public static async runMigration(): Promise<{ success: boolean; message: string }> {
    try {
      // First clean up duplicates
      const cleanupResult = await this.cleanupDuplicateOtps();
      if (!cleanupResult.success) {
        return cleanupResult;
      }

      // Then ensure unique index
      const indexResult = await this.ensureUniqueIndex();
      if (!indexResult.success) {
        return indexResult;
      }

      return {
        success: true,
        message: `Migration completed successfully. ${cleanupResult.message}`,
      };
    } catch (error: any) {
      return {
        success: false,
        message: humanizeClientError(
          error,
          'The OTP cleanup migration could not be completed. Please try again.'
        ),
      };
    }
  }
}

// If running this file directly
if (require.main === module) {
  (async () => {
    try {
      // Connect to MongoDB (adjust connection string as needed)
      await mongoose.connect(
        process.env.MONGODB_URI || 'mongodb://localhost:27017/your-database'
      );

      const result = await OtpMigration.runMigration();
      console.log(result.message);

      await mongoose.disconnect();
      process.exit(result.success ? 0 : 1);
    } catch (error) {
      console.error('Migration script error:', error);
      process.exit(1);
    }
  })();
}
