import { NextResponse } from "next/server";
import { getSessionCustomer, updateCustomerProfile } from "../../../lib/customerAuth";
import { normalizeVatId, isValidVatId } from "@einfach-produktiv/invoicing";

export async function GET() {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ profile: null }, { status: 401 });
  return NextResponse.json({ profile: session.customer });
}

export async function PATCH(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const body = await request.json().catch(() => null);
  const {
    firstName,
    lastName,
    street,
    zip,
    city,
    country,
    companyName,
    vatId,
    hasDifferentShippingAddress,
    shippingFirstName,
    shippingLastName,
    shippingCompanyName,
    shippingDeliveryMethod,
    shippingStreet,
    shippingPackstationNumber,
    shippingPostNumber,
    shippingZip,
    shippingCity,
    shippingCountry,
    shippingContactEmail,
    shippingContactPhone,
  } = body ?? {};
  if (
    typeof firstName !== "string" ||
    !firstName ||
    typeof lastName !== "string" ||
    !lastName ||
    typeof street !== "string" ||
    !street ||
    typeof zip !== "string" ||
    !zip ||
    typeof city !== "string" ||
    !city ||
    typeof country !== "string" ||
    !country
  ) {
    return NextResponse.json({ ok: false, reason: "Bitte alle Pflichtfelder ausfüllen." }, { status: 400 });
  }
  // Both independently optional (see Customers.ts's own comment) — only
  // format-checked when actually provided, same as the backend field itself.
  const normalizedVatId = typeof vatId === "string" && vatId ? normalizeVatId(vatId) : undefined;
  if (normalizedVatId && !isValidVatId(normalizedVatId)) {
    return NextResponse.json({ ok: false, reason: "Ungültiges USt-IdNr.-Format (z. B. DE123456789)." }, { status: 400 });
  }

  // Same shape as the checkout's own shipping-address-override validation
  // (api/checkout/route.ts) — required fields only apply when the toggle
  // is actually on, since this whole block is optional otherwise.
  if (hasDifferentShippingAddress) {
    if (
      typeof shippingFirstName !== "string" ||
      !shippingFirstName ||
      typeof shippingLastName !== "string" ||
      !shippingLastName ||
      (shippingDeliveryMethod !== "address" && shippingDeliveryMethod !== "packstation") ||
      typeof shippingZip !== "string" ||
      !shippingZip ||
      typeof shippingCity !== "string" ||
      !shippingCity ||
      typeof shippingCountry !== "string" ||
      !shippingCountry
    ) {
      return NextResponse.json({ ok: false, reason: "Bitte alle Pflichtfelder der Lieferadresse ausfüllen." }, { status: 400 });
    }
    if (shippingDeliveryMethod === "address" && !shippingStreet) {
      return NextResponse.json({ ok: false, reason: "Bitte Straße und Hausnummer der Lieferadresse angeben." }, { status: 400 });
    }
    if (shippingDeliveryMethod === "packstation" && (!shippingPackstationNumber || !shippingPostNumber)) {
      return NextResponse.json({ ok: false, reason: "Bitte Packstation- und Postnummer der Lieferadresse angeben." }, { status: 400 });
    }
  }

  const result = await updateCustomerProfile(session.token, session.customer.id, {
    firstName,
    lastName,
    deliveryMethod: "address",
    street,
    zip,
    city,
    country,
    companyName: typeof companyName === "string" && companyName ? companyName : undefined,
    vatId: normalizedVatId,
    hasDifferentShippingAddress: Boolean(hasDifferentShippingAddress),
    shippingFirstName: hasDifferentShippingAddress ? shippingFirstName : undefined,
    shippingLastName: hasDifferentShippingAddress ? shippingLastName : undefined,
    shippingCompanyName: hasDifferentShippingAddress && shippingCompanyName ? shippingCompanyName : undefined,
    shippingDeliveryMethod: hasDifferentShippingAddress ? shippingDeliveryMethod : undefined,
    shippingStreet: hasDifferentShippingAddress ? shippingStreet : undefined,
    shippingPackstationNumber: hasDifferentShippingAddress ? shippingPackstationNumber : undefined,
    shippingPostNumber: hasDifferentShippingAddress ? shippingPostNumber : undefined,
    shippingZip: hasDifferentShippingAddress ? shippingZip : undefined,
    shippingCity: hasDifferentShippingAddress ? shippingCity : undefined,
    shippingCountry: hasDifferentShippingAddress ? shippingCountry : undefined,
    shippingContactEmail: hasDifferentShippingAddress && shippingContactEmail ? shippingContactEmail : undefined,
    shippingContactPhone: hasDifferentShippingAddress && shippingContactPhone ? shippingContactPhone : undefined,
  });
  return NextResponse.json(result, { status: result.ok ? 200 : 400 });
}
