// It's very important to specify the .js extension here, otherwise Vercel
// won't be able to import it (even though the file is named .ts).
// import { handler as globalHandler } from "./common/index.js";

// This is a workaround for deploying in vercel, which forces us to use
// file-based routes in the /api folder. We just re-export the global handler
// from the `start.ts` file that we also use for local development.
//
// In vercel.json, we have a rewrite rule that rewrites /gemini to /api/gemini.
// Ths is necessary so that all requests under the /gemini route go to this handler.

export const config = { runtime: "edge" };

const GEMINI_HOST = (
    process.env.GEMINI_BASE_URL ?? ""
).replace(/\/+$/, "");


/** Minimal CORS helper (mirrors the request's Origin if present). */
function corsHeaders(requestHeaders: Headers): Headers {
  const h = new Headers();
  h.set("Access-Control-Allow-Origin", requestHeaders.get("origin") ?? "*");
  h.set(
    "Access-Control-Allow-Headers",
    requestHeaders.get("access-control-request-headers") ??
      "content-type,authorization"
  );
  h.set(
    "Access-Control-Allow-Methods",
    requestHeaders.get("access-control-request-method") ?? "POST,OPTIONS"
  );
  h.set("Access-Control-Max-Age", "86400");
  return h;
}

export default async function handler(req: Request): Promise<Response> {
  // 1️⃣  Handle CORS pre-flight locally.
  if (req.method === "OPTIONS") {
    return new Response(null, {
      status: 204,
      headers: corsHeaders(req.headers),
    });
  }

  if (req.method !== "POST") {
    return new Response("Method Not Allowed", { status: 405 });
  }

  if (!process.env.GEMINI_BASE_URL || !process.env.GEMINI_API_KEY) {
    return new Response("GEMINI_BASE_URL or GEMINI_API_KEY is not set", { status: 500 });
  }

  const key = process.env.GEMINI_API_KEY;
  if (!key) {
    return new Response("Missing GEMINI_API_KEY", { status: 500 });
  }

  // 2️⃣  Forward the request body straight through to Gemini.
  const upstream = await fetch(`${GEMINI_HOST}/chat/completions`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${key}`,
      "Content-Type": "application/json",
    },
    body: req.body, // already a stream; no buffering
  });

  // 3️⃣  If Gemini errs, surface the JSON so the caller can react.
  if (!upstream.ok) {
    return new Response(await upstream.text(), {
      status: upstream.status,
      headers: corsHeaders(req.headers),
    });
  }

  // 4️⃣  Relay Gemini's streaming/SSE response untouched.
  //     Edge runtime will automatically apply backpressure.
  const headers = corsHeaders(req.headers);
  headers.set(
    "Content-Type",
    upstream.headers.get("content-type") ?? "text/event-stream"
  );
  headers.set("Cache-Control", "no-cache");
  headers.set("X-Accel-Buffering", "no"); // disable Nginx buffering (proxy-friendly)

  return new Response(upstream.body, {
    status: 200,
    headers,
  });
}
