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

export async function POST(req: NextRequest) {
  const accessToken = req.cookies.get(ACCESS_COOKIE)?.value;
  const refreshToken = req.cookies.get(REFRESH_COOKIE)?.value;
  const sessionNonce = req.cookies.get(NONCE_COOKIE)?.value;
  const backendRes = refreshToken
    ? await fetch(getBackendUrl("auth/logout"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        ...(sessionNonce ? { "X-LedgerOne-Session-Nonce": sessionNonce } : {}),
        "User-Agent": req.headers.get("user-agent") ?? "",
        "X-Forwarded-For": req.headers.get("x-forwarded-for") ?? "",
      },
      body: JSON.stringify({ refreshToken }),
    })
    : null;

  const payload = backendRes
    ? await backendRes.text()
    : JSON.stringify({
      data: { message: "Logged out." },
      meta: { timestamp: new Date().toISOString(), version: "v1" },
      error: null,
    });
  const res = new NextResponse(payload, {
    status: backendRes?.status ?? 200,
    headers: { "Content-Type": backendRes?.headers.get("content-type") ?? "application/json" },
  });
  clearAuthCookies(res);
  return res;
}
