import { business, finance } from '../index.js';
import type { TCurrency } from './currency.js';

export type TInvoiceStatus = 'draft' | 'invoice' | 'paid' | 'refunded';

export type TInvoiceItem = {
  position: number;
  name: string;
  articleNumber?: string;
  unitType: string;
  unitQuantity: number;
  unitNetPrice: number;
  vatPercentage: number;
};

export type TInvoiceEnvelope<
  TYPE extends 'creditnote' | 'debitnote',
  FIELDS,
> = business.TLetterEnvelope<
  'invoice',
  {
    invoiceId: string;
    invoiceType: TYPE;
    status: TInvoiceStatus;
    items: TInvoiceItem[];
    periodOfPerformance?: {
      from: number;
      to: number;
    };
    deliveryDate?: number;
    dueInDays: number;
    reverseCharge: boolean;
    /**
     * buyer reference is an optional field, that helps the buyer to identify the invoice
     */
    buyerReference?: string;
    /**
     * also a kind of reference, esspecially needed for circular xinvoice support.
     */
    electronicAddress?: {
      scheme: string;
      value: string;
    };
    printResult?: {
      pdfBufferString: string;
      totalNet: number;
      totalGross: number;
      vatGroups: {
        percentage: number;
        items: TInvoiceItem[];
      };
    };
    notes: string[];
    paymentOptions?: finance.IPaymentOptionInfo;
    currency: TCurrency;
  } & FIELDS
>;

export type TCreditNote = TInvoiceEnvelope<'creditnote', {}>;
export type TDebitNote = TInvoiceEnvelope<'debitnote', {}>;

export type TInvoice = TCreditNote | TDebitNote;

// Legacy type for backward compatibility
export interface IInvoiceItem extends TInvoiceItem {}
