import { NextResponse } from "next/server";
import { TOKEN_COOKIE } from "@/lib/session";

const API_URL = process.env.NEXT_PUBLIC_API_URL;

/** Thin proxy to Laravel POST /auth/google — see login/route.ts for the cookie pattern. */
export async function POST(request: Request) {
  const body = await request.json();

  const apiRes = await fetch(`${API_URL}/auth/google`, {
    method: "POST",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: JSON.stringify(body),
  });

  const data = await apiRes.json();

  if (!apiRes.ok) {
    return NextResponse.json(data, { status: apiRes.status });
  }

  const user = data.data.user;
  // Google can't supply date_of_birth — the button uses this to decide
  // whether to send the user to /complete-profile instead of home.
  const profileComplete = Boolean(user.phone && user.date_of_birth);

  const response = NextResponse.json({ data: { user, profileComplete } });

  response.cookies.set({
    name: TOKEN_COOKIE,
    value: data.data.token,
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });

  return response;
}
