"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAttestationServiceHandlers = registerAttestationServiceHandlers;
exports.toPredicateEnvelope = toPredicateEnvelope;
const disclosure_role_1 = require("../../srv/middleware/disclosure-role");
const REQUIRED = {
    Public: 'public_only',
    Disclosed: 'legitimate_interest',
    Authority: 'authority'
};
/**
 * Wire the disclosure-role middleware + per-entity tier gates on the given
 * CAP service. Idempotent in the sense that re-registering on the same
 * service instance would just stack hooks (CAP allows that, but consumers
 * should call this once from their service's `init()`).
 */
function registerAttestationServiceHandlers(srv, db) {
    // 1. Populate req.disclosureRole on every incoming request. The handler
    //    no-ops if there's no req.user (anonymous → public_only default).
    srv.before('*', async (req) => {
        await (0, disclosure_role_1.attachDisclosureRole)(req, db);
    });
    // 2. Gate per-entity reads. Service handlers run AFTER the before('*')
    //    hook so the role is already on req. We use entity-specific before
    //    handlers so the rejection fires before CAP runs the DB query.
    srv.before('READ', 'Disclosed', makeTierGate('Disclosed'));
    srv.before('READ', 'Authority', makeTierGate('Authority'));
}
function makeTierGate(tier) {
    const required = REQUIRED[tier];
    return (req) => {
        const actual = req.disclosureRole;
        if (!(0, disclosure_role_1.meetsDisclosure)(actual, required)) {
            return req.reject(403, `disclosure tier '${tier}' requires role '${required}'; caller has '${actual ?? 'public_only'}'`);
        }
    };
}
/**
 * Shape a `PredicateAttestations` row (or the `issuePredicateAttestation` job
 * result) into the PAC proof envelope. Pure/synchronous so consumers can call
 * it without any NIGHTGATE service context.
 */
function toPredicateEnvelope(row) {
    return {
        digestMultibase: row.valueCommitment ?? null,
        claim: {
            predicate: row.predicate,
            threshold: String(row.threshold),
            unit: row.unit ?? null
        },
        proof: {
            system: 'midnight-compact',
            circuit: 'provePredicate',
            verificationMethod: row.contractAddress,
            proofValue: row.provenTxHash ?? ''
        }
    };
}
