/**
 * Recover an Interview & Media Prep session's creation time from its id.
 *
 * Both session writers mint ids as `imp_${Date.now()}_${random}` (see the create
 * and duplicate routes in routes/interviewMediaPrep.ts and the AI generate route
 * in routes/aiContextInterviewMediaPrep.ts), so the creation instant is embedded
 * in the id itself. Records written before the subschema declared `createdAt`
 * lost the stored value to Mongoose strict mode; this reads it back.
 *
 * Shared by the read path (enrich responses on the fly) and the startup backfill
 * (persist the recovered value) so the parsing rules live in exactly one place.
 */

/** Matches the `imp_<epochMillis>_<random>` ids the session writers generate. */
const SESSION_ID_TIMESTAMP = /^imp_(\d{10,14})_/;

/** Reject timestamps outside a plausible window — a malformed id must not become a date. */
const EARLIEST_PLAUSIBLE = Date.UTC(2020, 0, 1);

/**
 * Returns the ISO creation timestamp encoded in a session id, or null when the id
 * does not carry a plausible one (caller should keep the "—" placeholder).
 */
export function deriveSessionCreatedAtFromId(id: unknown): string | null {
  if (typeof id !== 'string') return null;

  const match = SESSION_ID_TIMESTAMP.exec(id);
  if (!match) return null;

  const ts = Number(match[1]);
  if (!Number.isFinite(ts)) return null;
  if (ts < EARLIEST_PLAUSIBLE) return null;
  if (ts > Date.now() + 24 * 60 * 60 * 1000) return null;

  return new Date(ts).toISOString();
}
