import { getSession } from "../db/sessions.js";
import { getSupabase } from "../db/client.js";
import { validateSession } from "../rules/validate.js";
import { transitionSession } from "../sessions/stateMachine.js";
import * as audit from "../audit/index.js";
import { readDecrypted } from "../artifacts/encrypt.js";
export async function finalizeTransaction(sessionId) {
    const session = await getSession(sessionId);
    if (!session)
        return { success: false, errors: [{ code: "NOT_FOUND", message: "Session not found" }] };
    if (session.status !== "QUALITY_PASS") {
        return { success: false, errors: [{ code: "INVALID_STATE", message: `Session must be QUALITY_PASS, got ${session.status}` }] };
    }
    const validation = await validateSession(sessionId, session.ori);
    if (!validation.valid) {
        return {
            success: false,
            errors: validation.errors.map((e) => ({ code: e.code, message: e.message })),
        };
    }
    const tcn = session.tcn ?? `${session.ori}_${Date.now()}_${randomHex(8)}`;
    const { data: bestCaptures } = await getSupabase()
        .from("fingerprint_captures")
        .select("finger_position, artifact_ref, width, height, quality_score")
        .eq("session_id", sessionId)
        .eq("is_best", true);
    const fingerprints = [];
    for (const c of bestCaptures ?? []) {
        if (c.artifact_ref) {
            const wsq = await readDecrypted(c.artifact_ref);
            fingerprints.push({
                finger_position: c.finger_position,
                wsq,
                width: c.width,
                height: c.height,
                quality_score: c.quality_score,
            });
        }
    }
    await transitionSession(sessionId, "PACKAGE_READY", undefined, tcn);
    await audit.audit({ session_id: sessionId, event_type: "package_built", payload: { tcn, fingerprint_count: fingerprints.length } });
    return {
        success: true,
        tcn,
        ansiNistPayload: Buffer.concat([Buffer.from(`STUB_ANSI_NIST_${sessionId}`), Buffer.from(JSON.stringify({ tcn, count: fingerprints.length }))]),
    };
}
import { randomBytes } from "node:crypto";
function randomHex(len) {
    return randomBytes(len).toString("hex");
}
//# sourceMappingURL=finalize.js.map