// Server-only — imported exclusively by app/api/checkout/route.ts. Kept
// out of lib/payload.ts on purpose, same reasoning as discountServer.ts's
// own comment about staying free of next/headers in a module that's also
// reachable from "use client" import graphs.
const PAYLOAD_URL = process.env.PAYLOAD_URL || "https://payload.mk360.de";
const TENANT_SLUG = "einfach-produktiv";
const SERVICE_SECRET = process.env.ORDER_SERVICE_SECRET || "";

// Resolved once per request rather than cached across requests — this
// instance only has 1 tenant today, but a module-level cache would be the
// kind of thing that silently goes stale the moment a second tenant shows
// up. Cheap enough (single indexed lookup) not to worry about at this
// traffic level.
async function resolveTenantId(): Promise<number | null> {
  const params = new URLSearchParams({ "where[slug][equals]": TENANT_SLUG, limit: "1" });
  const res = await fetch(`${PAYLOAD_URL}/api/tenants?${params}`, { cache: "no-store" });
  if (!res.ok) return null;
  const data: { docs?: { id: number }[] } = await res.json();
  return data.docs?.[0]?.id ?? null;
}

export type OrderItemInput = {
  productId: number;
  productName: string;
  quantity: number;
  unitPrice: number;
  taxRatePercent: number;
  bundleContents: string | null;
};

export type CreateOrderInput = {
  customerId: number;
  customerFirstName: string;
  customerLastName: string;
  customerEmail: string;
  deliveryMethod: "address" | "packstation";
  street?: string;
  packstationNumber?: string;
  postNumber?: string;
  zip: string;
  city: string;
  country: string;
  newsletterOptIn: boolean;
  items: OrderItemInput[];
  subtotal: number;
  shippingCost: number;
  shippingMethodTitle: string;
  paymentMethodTitle: string;
  discountCode: string | null;
  discountAmount: number;
  total: number;
};

export type CreatedOrder = { orderNumber: string; createdAt: string; invoiceNumber: string; invoiceIssuedAt: string };

export async function createOrder(input: CreateOrderInput): Promise<CreatedOrder | null> {
  const tenantId = await resolveTenantId();
  if (tenantId == null) {
    console.error("createOrder: could not resolve tenant id");
    return null;
  }

  const res = await fetch(`${PAYLOAD_URL}/api/orders`, {
    method: "POST",
    headers: {
      "x-order-service-secret": SERVICE_SECRET,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      tenant: tenantId,
      customer: input.customerId,
      customerFirstName: input.customerFirstName,
      customerLastName: input.customerLastName,
      customerEmail: input.customerEmail,
      deliveryMethod: input.deliveryMethod,
      street: input.street,
      packstationNumber: input.packstationNumber,
      postNumber: input.postNumber,
      zip: input.zip,
      city: input.city,
      country: input.country,
      newsletterOptIn: input.newsletterOptIn,
      items: input.items.map((i) => ({
        product: i.productId,
        productName: i.productName,
        quantity: i.quantity,
        unitPrice: i.unitPrice,
        taxRatePercent: i.taxRatePercent,
        bundleContents: i.bundleContents,
      })),
      subtotal: input.subtotal,
      shippingCost: input.shippingCost,
      shippingMethodTitle: input.shippingMethodTitle,
      paymentMethodTitle: input.paymentMethodTitle,
      discountCode: input.discountCode,
      discountAmount: input.discountAmount,
      total: input.total,
    }),
  });

  if (!res.ok) {
    console.error(`createOrder: Payload returned ${res.status} ${res.statusText}`);
    return null;
  }

  const data: { doc: { orderNumber: string; createdAt: string; invoiceNumber: string; invoiceIssuedAt: string } } = await res.json();
  return {
    orderNumber: data.doc.orderNumber,
    createdAt: data.doc.createdAt,
    invoiceNumber: data.doc.invoiceNumber,
    invoiceIssuedAt: data.doc.invoiceIssuedAt,
  };
}
