import mongoose from 'mongoose';
import SyncSession from '../models/syncSession';
import SyncTrackingEvent from '../models/syncTrackingEvent';
import SyncResourceUsage from '../models/syncResourceUsage';
import SyncSessionPeriod from '../models/syncSessionPeriod';
import dbConfig from '../config/db';
import 'dotenv/config';

// The old unique index on (user, local_id) let a second device (or a
// reinstall) silently overwrite an unrelated session/event/sample for the
// same employee, because the client's local_id is only unique per device,
// not per employee. The models now declare a stricter index instead
// (device_name or resolved session added in), but Mongoose's autoIndex only
// ADDS indexes on startup — it never drops old ones — so the old, looser
// unique constraint has to be dropped explicitly here before the new one can
// take over.
async function fixSyncUniqueIndexes() {
  await dbConfig();
  console.log('Connected to DB');

  const targets = [
    { model: SyncSession, name: 'SyncSession' },
    { model: SyncTrackingEvent, name: 'SyncTrackingEvent' },
    { model: SyncResourceUsage, name: 'SyncResourceUsage' },
    { model: SyncSessionPeriod, name: 'SyncSessionPeriod' },
  ];

  for (const { model, name } of targets) {
    const indexes = await model.collection.indexes();
    const stale = indexes.find(
      (idx) => JSON.stringify(idx.key) === JSON.stringify({ user: 1, local_id: 1 }),
    );

    if (!stale) {
      console.log(`${name}: no stale (user, local_id) index found, skipping`);
      continue;
    }

    console.log(`${name}: dropping stale index "${stale.name}"`);
    await model.collection.dropIndex(stale.name!);
  }

  console.log('Syncing new indexes declared on the models...');
  for (const { model, name } of targets) {
    await model.syncIndexes();
    console.log(`${name}: indexes now`, await model.collection.indexes());
  }

  console.log('Done');
  await mongoose.disconnect();
}

fixSyncUniqueIndexes().catch((error) => {
  console.error('Migration failed:', error);
  mongoose.disconnect();
});
