// ── API: login voor de kantoorbrede auth-gate ────────────────────────────────
// Vergelijkt het ingevoerde wachtwoord constant-time met APP_WACHTWOORD en
// zet bij match een HMAC-signed sessiecookie (lib/auth.ts).

import { type NextRequest, NextResponse } from "next/server";
import {
  heeftAuthGate,
  maakSessieCookie,
  valideerWachtwoord,
  SESSIE_COOKIE_NAAM,
  SESSIE_COOKIE_MAX_AGE,
} from "@/lib/auth";

export async function POST(request: NextRequest) {
  if (!heeftAuthGate()) {
    return NextResponse.json({ ok: true });
  }

  let wachtwoord: string;
  try {
    const body = await request.json();
    wachtwoord = typeof body?.wachtwoord === "string" ? body.wachtwoord : "";
  } catch {
    wachtwoord = "";
  }

  if (!valideerWachtwoord(wachtwoord)) {
    return NextResponse.json({ fout: "Ongeldig wachtwoord" }, { status: 401 });
  }

  const response = NextResponse.json({ ok: true });
  response.cookies.set(SESSIE_COOKIE_NAAM, maakSessieCookie(), {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: SESSIE_COOKIE_MAX_AGE,
  });
  return response;
}
