import { runEvidenceSelectSql } from "../internal/sql.js";
import { isRecord, mapRunEvidence } from "../internal/rowMappers.js";
export class RunEvidenceRepository {
    #db;
    constructor(db) {
        this.#db = db;
    }
    upsertRunEvidence(input) {
        const now = new Date().toISOString();
        const existing = this.findRunEvidence(input.runId);
        this.#db
            .prepare(`INSERT INTO run_proof_evidence (
           run_id,
           changed_files_json,
           validations_json,
           warnings_json,
           patch_files_json,
           created_at,
           updated_at
         )
         VALUES (?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(run_id)
         DO UPDATE SET
           changed_files_json = excluded.changed_files_json,
           validations_json = excluded.validations_json,
           warnings_json = excluded.warnings_json,
           patch_files_json = excluded.patch_files_json,
           updated_at = excluded.updated_at`)
            .run(input.runId, JSON.stringify(input.changedFiles), JSON.stringify(input.validations), JSON.stringify(input.warnings), JSON.stringify(input.patchFiles ?? []), existing?.createdAt ?? now, now);
        return this.getRunEvidence(input.runId);
    }
    getRunEvidence(runId) {
        const evidence = this.#db
            .prepare(runEvidenceSelectSql("WHERE run_id = ?"))
            .get(runId);
        return mapRunEvidence(evidence);
    }
    findRunEvidence(runId) {
        const evidence = this.#db
            .prepare(runEvidenceSelectSql("WHERE run_id = ?"))
            .get(runId);
        return isRecord(evidence) ? mapRunEvidence(evidence) : undefined;
    }
}
