import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();

    // ✅ Use NEXT_PUBLIC or a server-side env variable
    const backendUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

    console.log("🔗 Calling backend:", `${backendUrl}/auth/login`); // ✅ debug log

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

    const data = await res.json();

    console.log("📦 Backend response:", res.status, data); // ✅ debug log

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

    const response = NextResponse.json(data);

    // ✅ Set httpOnly cookie
    response.cookies.set("token", data.access_token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24,
      path: "/",
    });

    return response;

  } catch (err) {
    console.error("❌ Login route error:", err); // ✅ see exact error
    return NextResponse.json(
      { message: "Internal server error", error: String(err) },
      { status: 500 }
    );
  }
}