import { getCompanySettings, type CompanySettings } from "./payload";
// "/einvoice" subpath, not the package's main entry — @e-invoice-eu/core
// pulls in Node-only dependencies that break a client bundle if reachable
// from a Client Component; see that package's own src/index.ts comment.
// This file is server-only (Next.js Server Components/Route Handlers),
// but importing from the main entry would still poison the bundle for
// any Client Component that transitively imports this same package.
import {
  renderInvoiceEInvoice,
  renderCorrectionInvoiceEInvoice,
  type InvoiceOrder,
  type CorrectionInvoiceKind,
  type CorrectionInvoiceOrder,
} from "@einfach-produktiv/invoicing/einvoice";

export type { CompanySettings };

// Fetched once by callers that need seller data for more than one purpose
// in the same request (e.g. orderEmail.ts also needs it for the email's
// legal footer, see buildLegalFooterLines() in emailTemplates.ts) — avoids
// a second identical company-settings round trip, unlike calling
// getCompanySettings() again inside each generator.
export async function getSellerForInvoice(): Promise<CompanySettings | null> {
  return getCompanySettings();
}

// Shared by app/lib/orderEmail.ts (checkout — attaches to the confirmation
// mail) and app/api/account/orders/[orderNumber]/invoice/route.ts (on-demand
// download) — same render call both times, so what a customer downloads
// later always matches what they were emailed. `seller` is passed in
// rather than fetched here, so a caller that already has it (see above)
// doesn't fetch it twice.
//
// As of 2026-07-23 (e-invoicing Phase 3), this produces a Factur-X-EN16931
// hybrid PDF/A-3 (visual PDF + embedded EN16931 XML) via
// @einfach-produktiv/invoicing's renderInvoiceEInvoice(), not a plain PDF —
// same visual document, but now machine-readable too. `Buffer.from()`
// wraps the library's `Uint8Array` return value — every downstream
// consumer (nodemailer's attachment `content`, the two on-demand download
// routes) already expects a `Buffer`, unchanged by this switch.
export async function generateInvoicePdf(order: InvoiceOrder, seller: CompanySettings | null): Promise<Buffer | null> {
  if (!seller) {
    console.error("generateInvoicePdf: no company-settings row found for tenant");
    return null;
  }
  return Buffer.from(await renderInvoiceEInvoice(order, seller));
}

// Frontend-side regeneration for the "Stornorechnung/Gutschrift
// herunterladen" download button — the real document was already
// generated once (Payload's Orders.ts afterChange hook) and emailed; this
// reproduces the identical PDF/A-3+XML from the order's own stored
// correctionInvoiceNumber/correctionInvoiceIssuedAt, same "deterministic
// regeneration, not file storage" approach as the original invoice.
export async function generateCorrectionInvoicePdf(
  kind: CorrectionInvoiceKind,
  order: CorrectionInvoiceOrder,
  seller: CompanySettings | null,
): Promise<Buffer | null> {
  if (!seller) {
    console.error("generateCorrectionInvoicePdf: no company-settings row found for tenant");
    return null;
  }
  return Buffer.from(await renderCorrectionInvoiceEInvoice(kind, order, seller));
}
