import { getRuntimeEnv } from "./runtime-env";

const env = getRuntimeEnv();

function allowedOrigin(request: Request) {
  const origin = request.headers.get("origin");
  if (!origin) return null;
  const portalUrl = String(
    (env as unknown as { KOC_PORTAL_URL?: string }).KOC_PORTAL_URL ?? "",
  ).trim();
  let portalOrigin = "";
  try {
    portalOrigin = portalUrl ? new URL(portalUrl).origin : "";
  } catch {
    portalOrigin = "";
  }
  return [portalOrigin, "http://localhost:3000", "http://localhost:3001"].includes(
    origin,
  )
    ? origin
    : null;
}

export function withPartnerCors(request: Request, response: Response) {
  const origin = allowedOrigin(request);
  if (origin) {
    response.headers.set("Access-Control-Allow-Origin", origin);
    response.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    response.headers.set(
      "Access-Control-Allow-Headers",
      [
        "Content-Type",
        "X-KOC-Task",
        "X-KOC-Claim",
        "X-KOC-Delegation",
        "X-KOC-Distribution",
        "X-KOC-File-Name",
        "X-KOC-Upload-Kind",
        "X-KOC-OCR-Exposure",
        "X-KOC-OCR-Views",
        "X-KOC-OCR-Status",
      ].join(", "),
    );
    response.headers.append("Vary", "Origin");
  }
  return response;
}

export function partnerOptions(request: Request) {
  return withPartnerCors(request, new Response(null, { status: 204 }));
}
