import { connectToDatabase } from '../lib/db';
import mongoose from 'mongoose';
import User from '../lib/models/User';
import Member from '../lib/models/Member';
import Attendance from '../lib/models/Attendance';
import Satsang from '../lib/models/Satsang';
import SatsangCenter from '../lib/models/SatsangCenter';
import Announcement from '../lib/models/Announcement';
import AuditLog from '../lib/models/AuditLog';
import ImportBatch from '../lib/models/ImportBatch';
// Environmental variables loaded from node environment

const MODELS_CHECKLIST = [
  { name: 'User', model: User, expectedKeys: ['email_1'] },
  { name: 'Member', model: Member, expectedKeys: ['mobile_1', 'name_text', 'cityId_1_areaId_1_isActive_1'] },
  { name: 'Attendance', model: Attendance, expectedKeys: ['satsangId_1_memberId_1', 'syncId_1', 'memberId_1_status_1_markedAt_-1', 'satsangId_1_status_1_markedAt_-1'] },
  { name: 'Satsang', model: Satsang, expectedKeys: ['occurrenceKey_1', 'startDateTime_1'] },
  { name: 'SatsangCenter', model: SatsangCenter, expectedKeys: ['location_2dsphere'] },
  { name: 'Announcement', model: Announcement, expectedKeys: ['lifecycle_filter_idx'] },
  { name: 'AuditLog', model: AuditLog, expectedKeys: ['timestamp_-1', 'entityId_1'] },
  { name: 'ImportBatch', model: ImportBatch, expectedKeys: ['batchId_1'] }
];

async function runIndexVerification() {
  console.log('--- GEETASHYAM DATABASE INDEX VERIFICATION RUNNER ---');

  if (!process.env.MONGODB_URI) {
    console.error('Error: MONGODB_URI environment variable is missing.');
    process.exit(1);
  }

  // Enforce required secrets to prevent runtime failures
  process.env.JWT_SECRET = process.env.JWT_SECRET || 'verify-temporary-secret-key-32chars';
  process.env.CRON_SECRET = process.env.CRON_SECRET || 'verify-temporary-cron-secret-token';

  try {
    await connectToDatabase();
    console.log('Successfully connected to production MongoDB cluster.');

    let overallSuccess = true;

    for (const item of MODELS_CHECKLIST) {
      console.log(`\nVerifying indexes for collection: "${item.model.collection.name}" (${item.name} model)`);
      
      const actualIndexes = await item.model.collection.indexes();
      const actualNames = actualIndexes.map((idx: any) => idx.name);

      console.log('  Actual Indexes in Database:', actualNames);
      console.log('  Expected Important Indexes:', item.expectedKeys);

      const missing: string[] = [];
      for (const expected of item.expectedKeys) {
        if (!actualNames.includes(expected)) {
          missing.push(expected);
        }
      }

      if (missing.length > 0) {
        console.log(`  ❌ STATUS: MISMATCH - Missing Expected Indexes:`, missing);
        overallSuccess = false;
      } else {
        console.log(`  ✓ STATUS: OK - All expected indexes match.`);
      }
    }

    console.log('\n--- VERIFICATION COMPLETED ---');
    if (overallSuccess) {
      console.log('Result: SUCCESS. All expectations matched correctly in the database.');
      process.exit(0);
    } else {
      console.log('Result: FAILED. There are missing indexes in the target database cluster.');
      process.exit(1);
    }

  } catch (error) {
    console.error('System error executing index checkup:', error);
    process.exit(1);
  }
}

runIndexVerification();
