import { getSession } from "../db/sessions.js";
import { getSupabase } from "../db/client.js";
import { loadORIConfig } from "./oriConfig.js";
export async function validateSession(sessionId, ori) {
    const session = await getSession(sessionId);
    if (!session) {
        return { valid: false, ori, errors: [{ field: "session", code: "NOT_FOUND", message: "Session not found" }], warnings: [], missing_required_fingers: [], missing_required_demographics: [], photo_required: false, photo_provided: false };
    }
    const config = await loadORIConfig(ori);
    const errors = [];
    const warnings = [];
    const missingDemographics = [];
    const missingFingers = [];
    if (!config.purpose_codes.allowed.includes(session.purpose)) {
        errors.push({ field: "purpose", code: "INVALID_PURPOSE", message: `Purpose ${session.purpose} not allowed for ORI ${ori}` });
    }
    const { data: demographics } = await getSupabase().from("subject_demographics").select("*").eq("session_id", sessionId).single();
    for (const field of config.demographics.required) {
        const val = demographics?.[field];
        if (val === undefined || val === null || String(val).trim() === "") {
            missingDemographics.push(field);
        }
    }
    if (missingDemographics.length > 0) {
        errors.push({ field: "demographics", code: "MISSING_REQUIRED", message: `Missing: ${missingDemographics.join(", ")}` });
    }
    const { data: captures } = await getSupabase()
        .from("fingerprint_captures")
        .select("finger_position, is_best, quality_score")
        .eq("session_id", sessionId)
        .eq("is_best", true);
    const bestPositions = new Set((captures ?? []).map((c) => c.finger_position));
    const requiredAll = [...config.fingerprints.required.rolls, ...config.fingerprints.required.slaps];
    for (const pos of requiredAll) {
        if (!bestPositions.has(pos))
            missingFingers.push(pos);
    }
    for (const c of captures ?? []) {
        if (c.quality_score < config.fingerprints.quality_threshold) {
            warnings.push({ field: c.finger_position, code: "LOW_QUALITY", message: `Quality ${c.quality_score} below threshold ${config.fingerprints.quality_threshold}` });
        }
    }
    if (missingFingers.length > 0) {
        errors.push({ field: "fingerprints", code: "MISSING_FINGERS", message: `Missing best capture for: ${missingFingers.join(", ")}` });
    }
    const photoRequired = config.photo.required;
    const photoProvided = false;
    return {
        valid: errors.length === 0,
        ori,
        errors,
        warnings,
        missing_required_fingers: missingFingers,
        missing_required_demographics: missingDemographics,
        photo_required: photoRequired,
        photo_provided: photoProvided,
    };
}
//# sourceMappingURL=validate.js.map