import { openDatabase } from "../database.js";
/**
 * Creates a new command run record.
 */
export function createCommandRun(requestId, projectId, command) {
    const db = openDatabase();
    db.prepare("INSERT INTO command_runs (request_id, project_id, command) VALUES (?, ?, ?)").run(requestId, projectId, command);
}
/**
 * Updates a command run with its result.
 */
export function updateCommandRun(requestId, exitCode, outputPreview, truncated) {
    const db = openDatabase();
    db.prepare("UPDATE command_runs SET exit_code = ?, output_preview = ?, truncated = ?, ended_at = CURRENT_TIMESTAMP WHERE request_id = ?").run(exitCode, outputPreview, truncated ? 1 : 0, requestId);
}
/**
 * Returns a command run by its request ID, or null if not found.
 */
export function getCommandRun(requestId) {
    const db = openDatabase();
    const row = db.prepare("SELECT * FROM command_runs WHERE request_id = ?").get(requestId);
    return row ?? null;
}
/**
 * Cleans up old command runs. Removes entries older than 7 days
 * and trims to at most 10,000 rows (keeping the most recent).
 */
export function cleanupOldRuns() {
    const db = openDatabase();
    // Delete runs older than 7 days
    const ageResult = db
        .prepare("DELETE FROM command_runs WHERE started_at < datetime('now', '-7 days')")
        .run();
    // Delete excess rows beyond the 10,000 limit (keep newest)
    const limitResult = db
        .prepare(`DELETE FROM command_runs WHERE request_id NOT IN (
        SELECT request_id FROM command_runs ORDER BY started_at DESC LIMIT 10000
      )`)
        .run();
    return ageResult.changes + limitResult.changes;
}
//# sourceMappingURL=command-runs.js.map