import { runSelectSql } from "../internal/sql.js";
import { isRecord, mapRun, sanitizeRunCapPolicy, } from "../internal/rowMappers.js";
import { clampLimit } from "../internal/cursors.js";
export class RunRepository {
    #db;
    constructor(db) {
        this.#db = db;
    }
    createRun(input) {
        const now = new Date().toISOString();
        const status = input.status ?? "queued";
        this.#db
            .prepare(`INSERT INTO runs (
           id,
           workspace_id,
           provider,
           status,
           title,
           runtime_session_id,
           source_work_item_id,
           source_repository_id,
           source_preparation_id,
           source_run_intent_id,
           branch_plan_id,
           branch_name,
           base_branch,
           cap_policy_json,
           attempt_count,
           previous_run_id,
           created_at,
           updated_at
         )
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
            .run(input.id, input.workspaceId, input.provider, status, input.title ?? null, input.runtimeSessionId ?? null, input.sourceWorkItemId ?? null, input.sourceRepositoryId ?? null, input.sourcePreparationId ?? null, input.sourceRunIntentId ?? null, input.branchPlanId ?? null, input.branchName ?? null, input.baseBranch ?? null, input.capPolicy
            ? JSON.stringify(sanitizeRunCapPolicy(input.capPolicy))
            : null, input.attemptCount ?? 1, input.previousRunId ?? null, now, now);
        return this.getRun(input.id);
    }
    updateRunRuntimeSession(id, runtimeSessionId) {
        const now = new Date().toISOString();
        this.#db
            .prepare("UPDATE runs SET runtime_session_id = ?, updated_at = ? WHERE id = ?")
            .run(runtimeSessionId, now, id);
        return this.getRun(id);
    }
    updateRunStatus(id, status, lastError) {
        const now = new Date().toISOString();
        this.#db
            .prepare("UPDATE runs SET status = ?, last_error = ?, updated_at = ? WHERE id = ?")
            .run(status, lastError ?? null, now, id);
        return this.getRun(id);
    }
    getRun(id) {
        const run = this.#db.prepare(runSelectSql("WHERE id = ?")).get(id);
        return mapRun(run);
    }
    findRun(id) {
        const run = this.#db.prepare(runSelectSql("WHERE id = ?")).get(id);
        return isRecord(run) ? mapRun(run) : undefined;
    }
    listRunsForWorkspace(workspaceId, limit = 100) {
        const rows = this.#db
            .prepare(runSelectSql("WHERE workspace_id = ? ORDER BY created_at DESC, id ASC LIMIT ?"))
            .all(workspaceId, clampLimit(limit));
        const result = [];
        for (const row of rows) {
            if (isRecord(row))
                result.push(mapRun(row));
        }
        return result;
    }
    getRunByRuntimeSessionId(runtimeSessionId) {
        const run = this.#db
            .prepare(runSelectSql("WHERE runtime_session_id = ? ORDER BY created_at DESC LIMIT 1"))
            .get(runtimeSessionId);
        return isRecord(run) ? mapRun(run) : undefined;
    }
}
