import { NextResponse } from "next/server";
import { validateDhlPostNumber } from "../../../lib/shippingDhl";

// Called from CheckoutContent.tsx's Postnummer field blur (Packstation
// delivery). Proxied through this Next.js route rather than fetched
// directly from the client the way VIES is (see validate-vat/route.ts) —
// DHL credentials are tenant-specific and live in Payload, unlike VIES's
// public EU endpoint, so the browser must never call Payload's DHL
// endpoint (or hold its own copy of tenant credentials) directly.
export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const postNumber = typeof body?.postNumber === "string" ? body.postNumber : "";
  const firstName = typeof body?.firstName === "string" ? body.firstName : "";
  const lastName = typeof body?.lastName === "string" ? body.lastName : "";
  if (!postNumber || !firstName || !lastName) {
    return NextResponse.json({ ok: false, reason: "Postnummer, Vorname und Nachname sind erforderlich." }, { status: 400 });
  }

  const result = await validateDhlPostNumber({ postNumber, firstName, lastName });
  return NextResponse.json(result);
}
