import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { setRefreshCookie, 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) {
    return NextResponse.json({ error: "no refresh token" }, { status: 401 });
  }

  try {
    const res = await axiosInstance.post(
      `${API_URL}/oauth/token/refresh`,
      { refresh_token: refreshToken },
      { headers: { "Content-Type": "application/json", Authorization: "" } }
    );

    const { access_token, refresh_token, expires_in } = res.data;

    const response = NextResponse.json({ access_token, expires_in }, { status: 200 });
    setRefreshCookie(response, refresh_token, host);
    return response;
  } catch (error) {
    const response = NextResponse.json(
      error.response?.data ?? { error: "Refresh request failed" },
      { status: 401 }
    );
    clearRefreshCookie(response, host);
    return response;
  }
}
