import { lt } from 'drizzle-orm'; import { getDb } from '../db'; import { fetchCache } from '../db/schema'; import { runAndCountChanges } from '../db/sqlite-result'; /** Delete cache rows older than a calendar-day cutoff; zero explicitly clears all rows. */ export function cleanupFetchCache(days: number, now: Date = new Date()): number { if (!Number.isSafeInteger(days) || days < 0) { throw new RangeError('Cache cleanup days must be a non-negative safe integer'); } const db = getDb(); return runAndCountChanges(db, () => { if (days === 0) return db.delete(fetchCache).run(); const cutoff = new Date(now); cutoff.setDate(cutoff.getDate() - days); return db.delete(fetchCache).where(lt(fetchCache.fetchedAt, cutoff)).run(); }); }