"use strict";
/**
 * ApprovalQueueStore -- Storage abstraction for the ApprovalGateEnforcer.
 *
 * Follows the same interface + InMemory pattern used by HealthMetricsStore
 * (src/observability/health-metrics-store.ts) so future drop-ins
 * (Redis, Prisma) can be swapped without changing the enforcer.
 *
 * Relationship to PR #24 (ApprovalQueue):
 *   PR #24 ships ApprovalQueue, which is a file-backed persistent queue
 *   coupled to the AutonomySpectrumEnforcer workflow (poll-based, HMAC
 *   token verification). That class is reused as-is for the autonomy-
 *   spectrum path.
 *
 *   This module is a SEPARATE, lighter-weight store designed for the
 *   ApprovalGateEnforcer's synchronous-blocking workflow. It holds
 *   PendingApproval records in memory and resolves them via Promise
 *   callbacks. No HMAC, no file I/O required here -- the enforcer layer
 *   owns replay-protection and audit integration.
 *
 * @connexum/ai-governance P3-T2
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryApprovalQueueStore = void 0;
const crypto = __importStar(require("crypto"));
// ---------------------------------------------------------------------------
// InMemoryApprovalQueueStore -- default implementation
// ---------------------------------------------------------------------------
/**
 * Default in-memory implementation of ApprovalQueueStore.
 *
 * All data is lost on process restart. Suitable for testing and single-
 * process deployments. Production deployments that span multiple processes
 * or require crash-recovery should use a Prisma or Redis-backed store.
 *
 * PT-APPROVAL-3: The `_decided` set tracks all approvalIds that have been
 * resolved or timed out. `resolve()` and `timeout()` silently return false
 * if the ID is already in this set, preventing duplicate decisions.
 */
class InMemoryApprovalQueueStore {
    records = new Map();
    _decided = new Set();
    insert(record) {
        const approvalId = `apg_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
        const entry = {
            ...record,
            approvalId,
            status: 'pending',
        };
        this.records.set(approvalId, entry);
        return approvalId;
    }
    get(approvalId) {
        return this.records.get(approvalId) ?? null;
    }
    resolve(approvalId, decision, approverId, reason) {
        // PT-APPROVAL-3: replay protection -- ignore if already decided.
        if (this._decided.has(approvalId))
            return false;
        const record = this.records.get(approvalId);
        if (!record || record.status !== 'pending')
            return false;
        record.status = decision;
        record.approverId = approverId;
        record.reason = reason;
        record.decidedAt = new Date().toISOString();
        this._decided.add(approvalId);
        return true;
    }
    timeout(approvalId) {
        if (this._decided.has(approvalId))
            return false;
        const record = this.records.get(approvalId);
        if (!record || record.status !== 'pending')
            return false;
        record.status = 'timed-out';
        record.decidedAt = new Date().toISOString();
        record.reason = 'Timed out waiting for human approval. Default action: deny.';
        this._decided.add(approvalId);
        return true;
    }
    getPending(filter) {
        const results = [];
        for (const record of this.records.values()) {
            if (record.status !== 'pending')
                continue;
            if (filter?.actionClass && record.actionClass !== filter.actionClass)
                continue;
            if (filter?.initiator && record.initiator !== filter.initiator)
                continue;
            results.push({ ...record });
        }
        return results.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
    }
    getAll() {
        return Array.from(this.records.values())
            .map(r => ({ ...r }))
            .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
    }
    prune(maxAgeMs = 86_400_000) {
        const cutoff = Date.now() - maxAgeMs;
        let removed = 0;
        for (const [id, record] of this.records) {
            if (record.status !== 'pending' && record.decidedAt) {
                if (new Date(record.decidedAt).getTime() < cutoff) {
                    this.records.delete(id);
                    this._decided.delete(id);
                    removed++;
                }
            }
        }
        return removed;
    }
}
exports.InMemoryApprovalQueueStore = InMemoryApprovalQueueStore;
//# sourceMappingURL=approval-queue-store.js.map