import { NextRequest, NextResponse } from "next/server";
import { createSessionToken, SESSION_COOKIE } from "@/lib/session";
import { withBase, COOKIE_PATH } from "@/lib/basePath";

/**
 * Local username + password login. Verifies the credentials against the backend
 * user directory (server-side, with the admin token) and, on success, mints the
 * session cookie with the user's roles.
 */
const BACKEND = process.env.BACKEND_INTERNAL_URL || "http://127.0.0.1:8000";
const TOKEN = process.env.ADMIN_API_TOKEN || "";

export async function POST(req: NextRequest): Promise<NextResponse> {
  const form = await req.formData();
  const email = String(form.get("email") || "").trim().toLowerCase();
  const password = String(form.get("password") || "");
  const fromRaw = String(form.get("from") || "/");
  const from = fromRaw.startsWith("/") && !fromRaw.startsWith("/login") ? fromRaw : "/";

  const fail = (code: string) => NextResponse.redirect(new URL(withBase(`/login?error=${code}&from=${encodeURIComponent(from)}`), req.url), 303);

  if (!email || !password) return fail("missing_credentials");

  let ok = false;
  let name = email;
  let roles: string[] = [];
  try {
    const res = await fetch(`${BACKEND}/api/users/verify`, {
      method: "POST",
      headers: { Authorization: `Bearer ${TOKEN}`, "content-type": "application/json" },
      body: JSON.stringify({ email, password }),
      cache: "no-store",
    });
    if (res.ok) {
      const j = await res.json();
      ok = !!j.ok;
      name = typeof j.name === "string" && j.name ? j.name : email;
      roles = Array.isArray(j.roles) ? j.roles.map(String) : [];
    }
  } catch {
    return fail("login_unavailable");
  }
  if (!ok) return fail("invalid_credentials");

  const session = await createSessionToken({ email, name, roles });
  const res = NextResponse.redirect(new URL(withBase(from), req.url), 303);
  res.cookies.set(SESSION_COOKIE, session, {
    httpOnly: true,
    sameSite: "lax",
    path: COOKIE_PATH,
    secure: process.env.NODE_ENV === "production",
    maxAge: 60 * 60 * 12,
  });
  return res;
}
