import { lt } from "drizzle-orm";
import type { Database } from "./db/client.js";
import { tourEvents } from "./db/schema.js";

const RETENTION_MONTHS = 13;

export function eventsCutoff(now = new Date()): Date {
	const cutoff = new Date(now);
	cutoff.setMonth(cutoff.getMonth() - RETENTION_MONTHS);
	return cutoff;
}

export async function purgeExpiredEvents(
	db: Database,
	now = new Date(),
): Promise<number> {
	const removed = await db
		.delete(tourEvents)
		.where(lt(tourEvents.occurredAt, eventsCutoff(now)))
		.returning({ id: tourEvents.id });
	return removed.length;
}
