import { isRecord } from "../internal/rowMappers.js";
/**
 * Durable store for the bridge-side Remote Control policy (default-deny). A
 * missing row means the category is denied; the policy engine
 * (resolveRemoteControlDecision) treats undefined as denied.
 */
export class RemoteControlPolicyRepository {
    #db;
    constructor(db) {
        this.#db = db;
    }
    get(workspaceId, category) {
        const row = this.#db
            .prepare(`SELECT category, enabled, risk_mode
         FROM remote_control_policy
         WHERE workspace_id = ? AND category = ?`)
            .get(workspaceId, category);
        return isRecord(row) ? mapRow(row) : undefined;
    }
    set(workspaceId, row) {
        this.#db
            .prepare(`INSERT INTO remote_control_policy (workspace_id, category, enabled, risk_mode, updated_at)
         VALUES (?, ?, ?, ?, ?)
         ON CONFLICT(workspace_id, category) DO UPDATE SET
           enabled = excluded.enabled,
           risk_mode = excluded.risk_mode,
           updated_at = excluded.updated_at`)
            .run(workspaceId, row.category, row.enabled ? 1 : 0, row.riskMode, new Date().toISOString());
    }
    listForWorkspace(workspaceId) {
        const rows = this.#db
            .prepare(`SELECT category, enabled, risk_mode
         FROM remote_control_policy
         WHERE workspace_id = ?
         ORDER BY category ASC`)
            .all(workspaceId);
        return rows.filter(isRecord).map(mapRow);
    }
}
function mapRow(row) {
    return {
        category: String(row.category),
        enabled: Number(row.enabled) === 1,
        riskMode: normalizeRiskMode(row.risk_mode),
    };
}
function normalizeRiskMode(value) {
    // Fail-closed: any unexpected value is treated as the safer 'confirm'.
    return value === "silent" ? "silent" : "confirm";
}
