/**
 * POST /api/water-admin-auth
 *
 * Body: { pin: string }
 * Side effect: sets the `wl_admin_session` cookie on success.
 *
 * Used by the mobile/PIN-only `/water/admin/login` portal. Brand is
 * hardcoded (Tuxedo-only — see CLAUDE.md "Public Storefront
 * Architecture"). All auth logic lives in
 * `src/lib/water-admin-pin-auth.ts`.
 */
import { NextResponse } from "next/server";
import { verifyAdminPin } from "@/lib/water-admin-pin-auth";
import { captureError } from "@/lib/sentry";

export async function POST(request: Request) {
  try {
    const { pin } = (await request.json()) as { pin?: string };
    if (!pin) {
      return NextResponse.json(
        { success: false, error: "Missing pin" },
        { status: 400 },
      );
    }
    const result = await verifyAdminPin(pin);
    if (!result.ok) {
      // Don't leak whether the PIN was wrong vs. not configured — both
      // are the same to a field attacker probing the endpoint.
      const status = result.error === "Invalid PIN" ? 401 : 403;
      return NextResponse.json(
        { success: false, error: "Invalid PIN" },
        { status },
      );
    }
    return NextResponse.json({ success: true });
  } catch (err) {
    captureError(err as Error, { path: "/api/water-admin-auth" });
    return NextResponse.json(
      { success: false, error: "Server error" },
      { status: 500 },
    );
  }
}