import { NextResponse } from "next/server";
import { normalizeVatId, isValidVatId } from "@einfach-produktiv/invoicing";
import { checkVatIdViaVies } from "@einfach-produktiv/invoicing/vies";

// Called from CheckoutContent.tsx on the USt-IdNr. field's blur, whenever
// the billing country is Österreich — the only cross-border-EU option this
// checkout offers besides Deutschland (domestic, exemption never applies)
// and Schweiz (non-EU export, a different exemption entirely, out of
// scope here). Gives the shopper immediate feedback on whether their VAT
// ID actually qualifies for the innergemeinschaftliche-Lieferung
// exemption, before they even submit — api/checkout/route.ts re-runs this
// exact same check server-side at submit time regardless (never trusts
// this response), since a VIES result could theoretically change between
// blur and submit.
export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const vatId = typeof body?.vatId === "string" ? body.vatId : "";
  if (!vatId) return NextResponse.json({ ok: false, reason: "USt-IdNr. fehlt." }, { status: 400 });

  const normalized = normalizeVatId(vatId);
  if (!isValidVatId(normalized)) {
    return NextResponse.json({ ok: true, valid: false, reason: "Ungültiges USt-IdNr.-Format." });
  }

  const result = await checkVatIdViaVies(normalized);
  if (!result.ok) {
    // `ok: false` here means "VIES couldn't confirm this one way or the
    // other" (unreachable, or the member state's own gateway is briefly
    // down — `MS_UNAVAILABLE`, which VIES itself answers 200 for, not an
    // error status) — NOT "confirmed invalid". Previously this branch
    // still answered `{ ok: true, valid: false }`, which the client reads
    // as a rejected VAT ID (`vatIdViesStatus = "invalid"`) instead of
    // "couldn't check right now" (`"unavailable"`) — a real, currently
    // registered VAT ID looked wrong to the customer whenever VIES (or
    // just Germany's own national gateway) had a hiccup.
    return NextResponse.json({ ok: false, reason: result.reason });
  }
  return NextResponse.json({ ok: true, valid: result.valid, name: result.name });
}
