import { randomUUID } from "node:crypto";
import { getSession } from "../db/sessions.js";
import { getSupabase } from "../db/client.js";
import { finalizeTransaction } from "../packaging/finalize.js";
import { StubVendorAdapter } from "./stubAdapter.js";
import * as audit from "../audit/index.js";
const vendorAdapter = new StubVendorAdapter();
export async function submit(sessionId, vendorName) {
    const session = await getSession(sessionId);
    if (!session)
        throw new Error("Session not found");
    if (session.status !== "PACKAGE_READY")
        throw new Error(`Session must be PACKAGE_READY, got ${session.status}`);
    const finalized = await finalizeTransaction(sessionId);
    if (!finalized.success || !finalized.ansiNistPayload || !finalized.tcn) {
        return {
            ackNak: "NAK",
            errors: finalized.errors ?? [{ code: "FINALIZE_FAILED", message: "Could not build transaction" }],
            respondedAt: new Date().toISOString(),
        };
    }
    const idempotencyKey = `${sessionId}_${Date.now()}`;
    const result = await vendorAdapter.submit({
        transactionBinary: finalized.ansiNistPayload,
        metadata: { sessionId, tcn: finalized.tcn, ori: session.ori },
        idempotencyKey,
    });
    await getSupabase().from("submission_records").insert({
        id: randomUUID(),
        session_id: sessionId,
        vendor: vendorName,
        request_id: idempotencyKey,
        tcn: result.tcn ?? finalized.tcn,
        ack_nak: result.ackNak,
        error_list: result.errors ?? [],
        raw_response: result.rawResponse ?? null,
        submitted_at: new Date().toISOString(),
        responded_at: result.respondedAt,
    });
    const newStatus = result.ackNak === "ACK" ? "ACCEPTED" : "REJECTED";
    await getSupabase().from("sessions").update({ status: newStatus, updated_at: new Date().toISOString() }).eq("id", sessionId);
    await audit.audit({
        session_id: sessionId,
        event_type: result.ackNak === "ACK" ? "ack_received" : "nak_received",
        payload: { ...result },
    });
    return result;
}
//# sourceMappingURL=submit.js.map