import { randomUUID } from 'crypto';
import { nexusEventBus } from '../../engines/event-bus.js';
function mapApproval(row) {
    return {
        id: row.id,
        missionId: row.mission_id ?? null,
        operativeId: row.operative_id,
        scope: row.scope ?? 'mission',
        scopeId: row.scope_id ?? null,
        action: row.action,
        description: row.description,
        payload: parsePayload(row.payload_json),
        status: row.status,
        decidedAt: row.decided_at ?? null,
        createdAt: row.created_at,
    };
}
function parsePayload(value) {
    if (!value)
        return null;
    try {
        const parsed = JSON.parse(value);
        return parsed && typeof parsed === 'object' ? parsed : null;
    }
    catch {
        return null;
    }
}
export function requestApproval(db, input) {
    const id = randomUUID();
    const scope = input.scope ?? 'mission';
    const scopeId = input.scopeId ?? (scope === 'mission' ? input.missionId ?? id : input.missionId ?? id);
    db.prepare(`
    INSERT INTO synapse_approvals (id, mission_id, operative_id, scope, scope_id, action, description, payload_json, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
  `).run(id, input.missionId ?? null, input.operativeId, scope, scopeId, input.action, input.description, JSON.stringify(input.payload ?? {}));
    nexusEventBus.emit('synapse.approval.requested', { approvalId: id, operativeId: input.operativeId, action: input.action });
    return getApproval(db, id);
}
export function resolveApproval(db, approvalId, decision) {
    db.prepare('UPDATE synapse_approvals SET status=?, decided_at=datetime(\'now\') WHERE id=?').run(decision, approvalId);
    const approval = getApproval(db, approvalId);
    if (approval) {
        nexusEventBus.emit('synapse.approval.resolved', { approvalId, decision });
    }
    return approval;
}
export function getApproval(db, approvalId) {
    const row = db.prepare('SELECT * FROM synapse_approvals WHERE id=?').get(approvalId);
    return row ? mapApproval(row) : null;
}
export function getPendingApprovals(db) {
    return db.prepare('SELECT * FROM synapse_approvals WHERE status=\'pending\' ORDER BY created_at ASC').all().map(mapApproval);
}
export function hasPendingApprovalForMission(db, missionId, scope) {
    const row = db.prepare(`
    SELECT id
    FROM synapse_approvals
    WHERE status='pending'
      AND (
        (? IS NOT NULL AND mission_id = ?)
        OR (? IS NOT NULL AND scope = ? AND scope_id = ?)
      )
    LIMIT 1
  `).get(missionId ?? null, missionId ?? null, scope?.scope ?? null, scope?.scope ?? null, scope?.scopeId ?? null);
    return Boolean(row);
}
