import { NextRequest, NextResponse } from "next/server";
import { getBackendUrl } from "@/lib/backend";
import { NONCE_COOKIE, REFRESH_COOKIE, clearAuthCookies, setAuthCookies } from "@/lib/auth-cookies";

export async function POST(req: NextRequest) {
  const refreshToken = req.cookies.get(REFRESH_COOKIE)?.value;
  const sessionNonce = req.cookies.get(NONCE_COOKIE)?.value;
  if (!refreshToken) {
    const res = NextResponse.json(
      {
        data: null,
        meta: { timestamp: new Date().toISOString(), version: "v1" },
        error: { message: "Missing refresh token." },
      },
      { status: 401 },
    );
    clearAuthCookies(res);
    return res;
  }

  const backendRes = await fetch(getBackendUrl("auth/refresh"), {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "User-Agent": req.headers.get("user-agent") ?? "",
      "X-Forwarded-For": req.headers.get("x-forwarded-for") ?? "",
      ...(sessionNonce ? { "X-LedgerOne-Session-Nonce": sessionNonce } : {}),
    },
    body: JSON.stringify({ refreshToken }),
  });
  const payload = await backendRes.text();
  const parsed = JSON.parse(payload) as { data?: { accessToken?: string; refreshToken?: string; sessionNonce?: string; [key: string]: unknown } };
  const responsePayload = backendRes.ok && parsed.data?.accessToken && parsed.data.refreshToken && parsed.data.sessionNonce
    ? JSON.stringify({ ...parsed, data: {} })
    : payload;
  const res = new NextResponse(responsePayload, {
    status: backendRes.status,
    headers: { "Content-Type": backendRes.headers.get("content-type") ?? "application/json" },
  });
  if (backendRes.ok && parsed.data?.accessToken && parsed.data.refreshToken && parsed.data.sessionNonce) {
    setAuthCookies(res, parsed.data.accessToken, parsed.data.refreshToken, parsed.data.sessionNonce);
  } else {
    clearAuthCookies(res);
  }
  return res;
}
