import { API_ORIGIN } from "@/lib/apiOrigin";
import { clientIpFrom } from "@/lib/clientIp";

/**
 * POST /api/v1/auth/login: the one auth call that doesn't go straight through the
 * /api/v1/* rewrite in next.config.ts (filesystem routes win over rewrites).
 *
 * The API records each login's location from the request IP, but behind this app it
 * only sees the server's address and ignores X-Forwarded-For. It does accept
 * `clientIp` in the body, so the server adds the visitor's IP here. A browser can't
 * know its own public IP, and a value sent by the client is replaced, not trusted.
 *
 * Status, body and every Set-Cookie (the refresh_token cookie, Path=/api/v1/auth)
 * are passed back unchanged, so the session still belongs to this origin.
 */
export async function POST(request: Request) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return Response.json(
      { success: false, statusCode: 400, message: "Request body must be JSON", path: "/api/v1/auth/login", timestamp: new Date().toISOString() },
      { status: 400 },
    );
  }

  // proxy.ts has already reduced X-Forwarded-For to the one trusted address.
  const ip = clientIpFrom(request.headers.get("x-forwarded-for"));
  const payload: Record<string, unknown> = body && typeof body === "object" && !Array.isArray(body) ? { ...body } : {};
  delete payload.clientIp;
  if (ip) payload.clientIp = ip;

  const headers: Record<string, string> = { "Content-Type": "application/json", Accept: "application/json" };
  if (ip) headers["X-Forwarded-For"] = ip;
  const ua = request.headers.get("user-agent");
  if (ua) headers["User-Agent"] = ua;

  let res: Response;
  try {
    res = await fetch(`${API_ORIGIN}/api/v1/auth/login`, { method: "POST", headers, body: JSON.stringify(payload), cache: "no-store" });
  } catch {
    return Response.json(
      { success: false, statusCode: 502, message: "Sign-in service is unreachable. Try again shortly.", path: "/api/v1/auth/login", timestamp: new Date().toISOString() },
      { status: 502 },
    );
  }

  const out = new Headers();
  for (const name of ["content-type", "retry-after", "ratelimit-limit", "ratelimit-remaining", "ratelimit-reset"]) {
    const v = res.headers.get(name);
    if (v) out.set(name, v);
  }
  for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
  out.set("cache-control", "no-store");

  return new Response(res.status === 204 ? null : await res.arrayBuffer(), { status: res.status, headers: out });
}
