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

/**
 * Dev login (Story 5 / PoC): signs in with just an email when Google OAuth is
 * not yet configured. Disable in production with ALLOW_DEV_LOGIN=false.
 */
export async function POST(req: NextRequest): Promise<NextResponse> {
  if (process.env.ALLOW_DEV_LOGIN === "false") {
    return NextResponse.json({ error: "Dev login disabled" }, { status: 403 });
  }

  const form = await req.formData();
  const email = String(form.get("email") || "admin@digt.ch").trim() || "admin@digt.ch";
  const fromRaw = String(form.get("from") || "/");
  const from = fromRaw.startsWith("/") && !fromRaw.startsWith("/login") ? fromRaw : "/";

  // The dev login is the superadmin escape hatch (never role-locked).
  const token = await createSessionToken({ email, name: email, roles: ["superadmin"] });
  const res = NextResponse.redirect(new URL(withBase(from), req.url));
  res.cookies.set(SESSION_COOKIE, token, {
    httpOnly: true,
    sameSite: "lax",
    path: COOKIE_PATH,
    secure: process.env.NODE_ENV === "production",
    maxAge: 60 * 60 * 12,
  });
  return res;
}
