import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { setRefreshCookie } from "@/lib/refreshCookie";

export async function POST(request) {
  const { uuid, code } = await request.json();
  const API_URL = process.env.NEXT_PUBLIC_API_URL;

  if (!uuid || !code) {
    return NextResponse.json({ error: "uuid and code are required" }, { status: 400 });
  }

  const jsonHeaders = { "Content-Type": "application/json", Authorization: "" };

  try {
    const verify = await axiosInstance.post(
      `${API_URL}/api/v1/user/verify-code`,
      { uuid, code },
      { headers: jsonHeaders }
    );

    const grant = verify.data?.data?.grant;
    if (!grant) {
      return NextResponse.json({ error: "grant not issued" }, { status: 400 });
    }

    const token = await axiosInstance.post(
      `${API_URL}/oauth/token`,
      { grant_type: "mobile", grant },
      { headers: jsonHeaders }
    );

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

    const response = NextResponse.json({ access_token, expires_in }, { status: 200 });
    setRefreshCookie(response, refresh_token, request.headers.get("host"));
    return response;
  } catch (error) {
    if (error.response) {
      return NextResponse.json(error.response.data, { status: error.response.status });
    }
    return NextResponse.json({ error: "Token request failed" }, { status: 500 });
  }
}
