import type { OrchestratorService } from '@platform-modules/chatgpt-orchestrator-core';

export interface RetentionHandle {
  days: number;
  close(): void;
}

export async function startRetention(service: OrchestratorService): Promise<RetentionHandle> {
  const days = Number.parseInt(process.env.CHATGPT_ORCHESTRATOR_RETENTION_DAYS ?? '30', 10);
  if (!Number.isInteger(days) || days < 1 || days > 3650) {
    throw new Error('CHATGPT_ORCHESTRATOR_RETENTION_DAYS must be an integer from 1 through 3650.');
  }

  const prune = async (): Promise<void> => {
    const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
    await service.pruneTerminalRuns(cutoff);
  };

  await prune();
  const timer = setInterval(() => { void prune().catch((error) => console.error('retention prune failed', error)); }, 6 * 60 * 60 * 1000);
  timer.unref();
  return { days, close: () => clearInterval(timer) };
}
