/**
 * POST /api/water-admin-auth
 *
 * Body: { brandId: string, pin: string }
 * Side effect: sets the `wl_admin_session` cookie on success.
 *
 * Used by the mobile/PIN-only `/water/admin/login` portal. The session
 * itself is created by `verifyWaterAdminPin()` in
 * `src/actions/water-log/settings.ts`, which is the single source of
 * truth for admin PIN verification.
 */
import { NextResponse } from "next/server";
import { verifyWaterAdminPin } from "@/actions/water-log/settings";
import { captureError } from "@/lib/sentry";

export async function POST(request: Request) {
  try {
    const { brandId, pin } = (await request.json()) as {
      brandId?: string;
      pin?: string;
    };
    if (!brandId || !pin) {
      return NextResponse.json(
        { success: false, error: "Missing brandId or pin" },
        { status: 400 },
      );
    }
    const result = await verifyWaterAdminPin(brandId, pin);
    if (!result.success) {
      // 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 },
    );
  }
}
