// Thin client for the backend's DHL custom endpoints (src/lib/endpoints/
// dhlValidatePostNumber.ts, dhlAutocompleteAddress.ts) — own copy per repo,
// unlike vies.ts/vatId.ts/tracking.ts (now shared via @einfach-produktiv/invoicing),
// since this proxies to Payload endpoints specific to this repo's own DHL wiring,
// not portable logic.
const PAYLOAD_URL = process.env.PAYLOAD_URL || "https://payload.mk360.de";
const TENANT_SLUG = "einfach-produktiv";

export async function validateDhlPostNumber(args: {
  postNumber: string;
  firstName: string;
  lastName: string;
}): Promise<{ ok: true; valid: boolean } | { ok: false; reason: string }> {
  const params = new URLSearchParams({ tenantSlug: TENANT_SLUG, ...args });
  try {
    const res = await fetch(`${PAYLOAD_URL}/api/dhl/validate-post-number?${params}`, {
      signal: AbortSignal.timeout(8000),
    });
    const data = await res.json();
    if (!res.ok || !data.ok) return { ok: false, reason: data.reason ?? "Postnummer konnte nicht geprüft werden." };
    return { ok: true, valid: Boolean(data.valid) };
  } catch {
    return { ok: false, reason: "Postnummer-Prüfung ist gerade nicht erreichbar." };
  }
}

export type DhlAddressSuggestion = {
  street: string;
  houseNumber?: string;
  zip: string;
  city: string;
  country: string;
};

export async function autocompleteDhlAddress(query: string): Promise<DhlAddressSuggestion[]> {
  if (query.trim().length < 3) return [];
  const params = new URLSearchParams({ tenantSlug: TENANT_SLUG, query });
  try {
    const res = await fetch(`${PAYLOAD_URL}/api/dhl/autocomplete-address?${params}`, {
      signal: AbortSignal.timeout(5000),
    });
    const data = await res.json();
    if (!res.ok || !data.ok) return [];
    return data.suggestions as DhlAddressSuggestion[];
  } catch {
    return [];
  }
}
