import { pruneChatEventsOlderThan } from 'officerdb';

// The durable chat event queue (chat_session_events) grows with every turn. Prune old rows so it
// stays bounded — a session's transcript (Claude's .jsonl) is the real record; the queue only needs
// enough history to cover reconnect replay, so a few days is generous.
const RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // keep 7 days
const INTERVAL_MS = 6 * 60 * 60 * 1000; // prune every 6h

export function startChatEventRetention(): void {
  const tick = async () => {
    try {
      await pruneChatEventsOlderThan(new Date(Date.now() - RETENTION_MS));
    } catch (err) {
      console.error('[chat-retention] prune failed:', err instanceof Error ? err.message : err);
    }
  };
  void tick(); // sweep once at startup
  setInterval(tick, INTERVAL_MS);
  console.log(
    `[chat-retention] pruning chat_session_events older than ${RETENTION_MS / 86_400_000}d, every ${INTERVAL_MS / 3_600_000}h`,
  );
}
