import type {
    OrchestratorPreparePayload,
    OrchestratorPrepareResponse,
} from "./data";
import { createLinkFlowError, isErrPayload, normalizeBaseUrl } from "./utils";
import { formatErrorDetail } from "@pkg/logger";
import { ERROR_CODES } from "@pkg/result";
import { settings } from "@pkg/settings";

export async function prepareOrchestratedSession(
    flowId: string,
    payload: OrchestratorPreparePayload,
): Promise<OrchestratorPrepareResponse> {
    const response = await fetch(
        `${normalizeBaseUrl(settings.orchestratorApiUrl)}/internal/sessions/prepare`,
        {
            method: "POST",
            headers: {
                "content-type": "application/json",
                "x-internal-api-key": settings.internalApiKey,
                "x-flow-id": flowId,
            },
            body: JSON.stringify(payload),
        },
    );

    let body: unknown = null;
    try {
        body = await response.json();
    } catch (error) {
        throw createLinkFlowError(
            flowId,
            ERROR_CODES.EXTERNAL_SERVICE_ERROR,
            "Invalid orchestrator response",
            "The orchestrator returned a response that could not be parsed",
            formatErrorDetail(error),
        );
    }

    if (!response.ok && body && typeof body === "object" && "error" in body) {
        const payloadError = (body as { error?: unknown }).error;
        if (isErrPayload(payloadError)) {
            throw payloadError;
        }
    }

    if (
        !body ||
        typeof body !== "object" ||
        !("data" in body) ||
        ("error" in body && body.error)
    ) {
        throw createLinkFlowError(
            flowId,
            ERROR_CODES.EXTERNAL_SERVICE_ERROR,
            "Unexpected orchestrator response",
            "The orchestrator response was missing the expected data payload",
            JSON.stringify(body),
        );
    }

    return body as OrchestratorPrepareResponse;
}
