/**
 * Normalised Amazon Ads (Sponsored Ads) invoice — the ONE shape the page, the
 * store and the iDempiere importer work with, whether the invoice came from the
 * Amazon Ads API (GET /invoices + /invoices/{id}) or from a downloaded PDF
 * (parseInvoicePdf.ts). Amounts are numbers in the invoice currency.
 */
export interface AdsInvoiceLine {
  campaignId?: string | null
  campaignName: string
  program?: string | null          // e.g. "SPONSORED PRODUCTS"
  costEventType?: string | null    // CLICKS | IMPRESSIONS
  costEventCount?: number | null   // clicks
  costPerUnit?: number | null      // average CPC
  amount: number                   // net line amount
  taxRate?: number | null          // seller-fee invoices: VAT rate of THIS line (rows can differ)
  tax?: number | null              // seller-fee invoices: VAT amount of this line
}

export interface AdsInvoice {
  /** 'ads' = Sponsored Ads invoice (default, also for rows stored before the field existed);
   *  'fee' = seller fee invoice from Seller Central → Tax Document Library → Seller Invoices */
  kind?: 'ads' | 'fee'
  isCreditNote?: boolean           // fee documents titled (STEUER)GUTSCHRIFT / CREDIT NOTE — totals are NEGATIVE
  originalInvoiceNo?: string | null // credit notes: "Ursprüngliche Rechnungsnummer" = the fee invoice they correct
  invoiceNo: string
  invoiceDate: string              // YYYY-MM-DD
  periodFrom?: string | null       // YYYY-MM-DD
  periodTo?: string | null
  dueDate?: string | null
  currency: string                 // EUR
  net: number
  tax: number
  gross: number
  taxRate?: number | null          // 19
  paymentMethod?: string | null    // DEDUCT_FROM_PAYMENT | CREDIT_CARD | ...
  paymentMethodLabel?: string | null
  status?: string | null           // PAID_IN_FULL | ISSUED | ...
  countryCode?: string | null      // DE
  issuer?: { name?: string; vatId?: string; address1?: string; postal?: string; city?: string; countryCode?: string } | null
  payer?: { name?: string; vatId?: string } | null
  lines: AdsInvoiceLine[]
  source: 'api' | 'pdf'
  documentAvailable?: boolean      // a PDF can be fetched/streamed for this invoice
  fileName?: string | null
}

export const PAYMENT_METHOD_LABELS: Record<string, string> = {
  DEDUCT_FROM_PAYMENT: 'Seller Payable (Auszahlungsabzug)',
  CREDIT_CARD: 'Kreditkarte',
  DIRECT_DEBIT: 'Lastschrift',
  ELECTRONIC_FUNDS_TRANSFER: 'Überweisung',
  PREPAY: 'Vorauszahlung',
  UNIFIED_BILLING: 'Unified Billing'
}

export const round2 = (n: any) => Math.round((Number(n) || 0) * 100) / 100
