/**
 * Backfill Interview & Media Prep session createdAt
 *
 * The session subschema used to declare neither createdAt nor updatedAt, so
 * Mongoose strict mode silently dropped both on every write: the routes set
 * them, the values never landed, and the listing rendered '-' for every row.
 * Declaring the fields fixes new rows, but rows written before that fix have no
 * timestamp at all and would show '-' forever.
 *
 * The value is recoverable rather than lost. Both writers mint ids as
 * `imp_${Date.now()}_${random}` — see routes/interviewMediaPrep.ts (create) and
 * routes/aiContextInterviewMediaPrep.ts (AI generate) — so the creation instant
 * is embedded in the id itself. This reads it back and persists it.
 *
 * Only additive: rows that already have a createdAt are never touched, and an id
 * that does not match the expected shape (or carries an implausible timestamp)
 * is skipped rather than guessed at. A row we cannot date keeps rendering the
 * '-' placeholder, which is honest.
 */

import { getModels } from '../models';
import { deriveSessionCreatedAtFromId } from './deriveSessionCreatedAt';

export async function backfillInterviewSessionCreatedAt(): Promise<number> {
  const { InterviewMediaPrep } = getModels();

  const docs = await InterviewMediaPrep.find({ 'sessions.createdAt': { $exists: false } });

  let patched = 0;

  for (const doc of docs) {
    let changed = false;

    for (const session of doc.sessions) {
      if (session.createdAt) continue;

      const derived = deriveSessionCreatedAtFromId(session.id);
      if (derived === null) continue;

      session.createdAt = derived;
      // Only seed updatedAt when it is absent; never overwrite a real edit time.
      if (!session.updatedAt) session.updatedAt = session.createdAt;

      changed = true;
      patched++;
    }

    if (changed) {
      doc.markModified('sessions');
      await doc.save();
    }
  }

  return patched;
}
