import { reindexFull } from './indexer';

// Nightly full-from-scratch reindex at 3am (server-local time). Uses reindexFull, so it builds into a
// fresh slot and atomically swaps it in only on success — the live index is never disrupted mid-build.
// Self-scheduling (a fresh setTimeout each night) rather than setInterval, so it always fires at 3am
// regardless of drift.

const REINDEX_HOUR = 3;

let timer: ReturnType<typeof setTimeout> | null = null;

function msUntilNextHour(hour: number): number {
  const now = new Date();
  const next = new Date(now);
  next.setHours(hour, 0, 0, 0);
  if (next <= now) next.setDate(next.getDate() + 1);
  return next.getTime() - now.getTime();
}

export function startNightlyReindex(): void {
  const schedule = () => {
    const ms = msUntilNextHour(REINDEX_HOUR);
    const at = new Date(Date.now() + ms);
    console.log(
      `[music] nightly full reindex scheduled for ${at.toLocaleString()} (in ${(ms / 3_600_000).toFixed(1)}h)`,
    );
    timer = setTimeout(async () => {
      console.log('[music] nightly full reindex starting');
      try {
        await reindexFull();
      } catch (err) {
        console.error('[music] nightly full reindex error:', err instanceof Error ? err.message : err);
      }
      schedule(); // reschedule for the following night
    }, ms);
  };
  schedule();
}

export function stopNightlyReindex(): void {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
}
