// Prepared SQL for the memory_tombstones table. Tombstones are intentionally NOT a foreign key
// against memories.id — the memory row is gone by the time the tombstone is written; the FK
// would either reject the insert or force ON DELETE SET NULL, both of which lose the audit
// signal. We therefore store memory_id as a denormalised TEXT column and accept that listing a
// tombstone tells you "this id existed in this scope at this time," not "follow the FK."
import { scopeCoordinateOf, scopeKindOf } from "./scope-key.js";
const INSERT_SQL = `
INSERT INTO memory_tombstones (
  id, memory_id, scope_kind, scope_coordinate, type, forgotten_at,
  forgetter_surface, reason
) VALUES (?,?,?,?,?,?,?,?)
`;
const LIST_BY_SCOPE_SQL = `
SELECT * FROM memory_tombstones
WHERE scope_kind = ? AND scope_coordinate = ?
ORDER BY forgotten_at ASC
`;
// `reason` is the only free-text tombstone column, so it is the only sealed one (ADR-0035).
function rowToTombstone(row, cipher) {
    const base = {
        id: row.id,
        memoryId: row.memory_id,
        scopeKind: row.scope_kind,
        scopeCoordinate: row.scope_coordinate,
        type: row.type,
        forgottenAt: row.forgotten_at,
        forgetterSurface: row.forgetter_surface,
    };
    return row.reason === null ? base : { ...base, reason: cipher.openString(row.reason) };
}
export function insertTombstoneRow(db, tombstone, cipher) {
    const reason = tombstone.reason === undefined ? null : cipher.sealString(tombstone.reason);
    db.prepare(INSERT_SQL).run(tombstone.id, tombstone.memoryId, tombstone.scopeKind, tombstone.scopeCoordinate, tombstone.type, tombstone.forgottenAt, tombstone.forgetterSurface, reason);
}
export function listTombstonesByScopeRows(db, scope, cipher) {
    const rows = db
        .prepare(LIST_BY_SCOPE_SQL)
        .all(scopeKindOf(scope), scopeCoordinateOf(scope));
    return rows.map((row) => rowToTombstone(row, cipher));
}
