import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { clearRefreshCookie, COOKIE_NAME } from "@/lib/refreshCookie";

export async function POST(request) {
  const API_URL = process.env.NEXT_PUBLIC_API_URL;
  const host = request.headers.get("host");
  const refreshToken = request.cookies.get(COOKIE_NAME)?.value;

  if (refreshToken) {
    try {
      await axiosInstance.post(
        `${API_URL}/oauth/logout`,
        { refresh_token: refreshToken },
        { headers: { "Content-Type": "application/json", Authorization: "" } }
      );
    } catch {
      // revoke best-effort; clearing the cookie below is what matters
    }
  }

  const response = NextResponse.json({ success: true }, { status: 200 });
  clearRefreshCookie(response, host);
  return response;
}
