import { openDatabase } from "./database.js";
import { cleanupOldRuns } from "./repositories/command-runs.js";
import { logger } from "../utils/logger.js";
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
let cleanupInterval = null;
/**
 * Cleans up old terminal sessions. Removes closed sessions older than 7 days
 * and trims to at most 1000 rows (keeping the most recent).
 * Active sessions (closed_at IS NULL) are never removed by the row limit.
 */
export function cleanupOldTerminalSessions() {
    const db = openDatabase();
    // Delete closed sessions older than 7 days
    const ageResult = db
        .prepare("DELETE FROM terminal_sessions WHERE closed_at IS NOT NULL AND created_at < datetime('now', '-7 days')")
        .run();
    // Delete excess closed rows beyond 1000 total (keep newest), never touching active sessions
    const limitResult = db
        .prepare(`DELETE FROM terminal_sessions WHERE closed_at IS NOT NULL AND terminal_id NOT IN (
        SELECT terminal_id FROM terminal_sessions WHERE closed_at IS NOT NULL
        ORDER BY created_at DESC LIMIT 1000
      )`)
        .run();
    return ageResult.changes + limitResult.changes;
}
/**
 * Runs all database cleanup tasks: terminal sessions and command runs.
 */
export function runCleanup() {
    try {
        const terminalDeleted = cleanupOldTerminalSessions();
        const commandDeleted = cleanupOldRuns();
        if (terminalDeleted > 0 || commandDeleted > 0) {
            logger.info(`Database cleanup: removed ${terminalDeleted} terminal sessions, ${commandDeleted} command runs`);
        }
        else {
            logger.debug("Database cleanup: nothing to remove");
        }
    }
    catch (err) {
        logger.error(`Database cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
    }
}
/**
 * Starts the periodic cleanup job. Runs immediately on startup,
 * then every 6 hours.
 */
export function startCleanupJob() {
    // Run immediately on startup
    runCleanup();
    // Schedule periodic cleanup every 6 hours
    cleanupInterval = setInterval(runCleanup, SIX_HOURS_MS);
    // Allow the process to exit even if the interval is active
    if (cleanupInterval.unref) {
        cleanupInterval.unref();
    }
}
/**
 * Stops the periodic cleanup job.
 */
export function stopCleanupJob() {
    if (cleanupInterval) {
        clearInterval(cleanupInterval);
        cleanupInterval = null;
    }
}
//# sourceMappingURL=cleanup.js.map