import { createHash, randomUUID } from "node:crypto";
import { getSupabase } from "../db/client.js";
import { getSession } from "../db/sessions.js";
import { transitionSession } from "../sessions/stateMachine.js";
import * as audit from "../audit/index.js";
import { writeEncrypted } from "../artifacts/encrypt.js";
const ARTIFACT_TTL_MS = 72 * 60 * 60 * 1000;
export async function storeCaptureResult(params) {
    const session = await getSession(params.session_id);
    if (!session)
        throw new Error("Session not found");
    const allowed = ["CREATED", "DEMOGRAPHICS_ENTERED", "FINGER_CAPTURE_IN_PROGRESS"];
    if (!allowed.includes(session.status)) {
        throw new Error(`Invalid state for capture: ${session.status}`);
    }
    if (session.status === "CREATED" || session.status === "DEMOGRAPHICS_ENTERED") {
        const t = await transitionSession(params.session_id, "FINGER_CAPTURE_IN_PROGRESS");
        if (!t.ok)
            throw new Error(t.error);
    }
    const hash = createHash("sha256").update(params.wsq_buffer).digest("hex");
    const expiresAt = new Date(Date.now() + ARTIFACT_TTL_MS);
    const artifactRef = await writeEncrypted(params.session_id, params.finger_position, params.attempt, params.wsq_buffer, expiresAt);
    const supabase = getSupabase();
    const { data: existing } = await supabase
        .from("fingerprint_captures")
        .select("quality_score")
        .eq("session_id", params.session_id)
        .eq("finger_position", params.finger_position);
    const maxExisting = existing?.length ? Math.max(...existing.map((r) => r.quality_score)) : 0;
    const isBest = params.quality_score >= maxExisting;
    if (isBest && (existing?.length ?? 0) > 0) {
        await supabase
            .from("fingerprint_captures")
            .update({ is_best: false })
            .eq("session_id", params.session_id)
            .eq("finger_position", params.finger_position);
    }
    await supabase.from("fingerprint_captures").insert({
        id: randomUUID(),
        session_id: params.session_id,
        finger_position: params.finger_position,
        capture_kind: params.capture_kind,
        attempt: params.attempt,
        is_best: isBest,
        quality_score: params.quality_score,
        quality_type: params.quality_type,
        image_hash: hash,
        artifact_ref: artifactRef,
        artifact_expires_at: expiresAt.toISOString(),
        width: params.width,
        height: params.height,
        captured_at: params.captured_at,
    });
    await audit.audit({
        session_id: params.session_id,
        event_type: "capture_completed",
        payload: { finger_position: params.finger_position, attempt: params.attempt, quality_score: params.quality_score },
    });
}
//# sourceMappingURL=storeCapture.js.map