import { Invoice } from '../../entities/Invoice';
import { INVOICE_WORKFLOW_STATUS } from '../../constants/invoiceWorkflowStatus';

export type TaxInvoiceOmTenYearAnchor = {
  invoiceId: string;
  fromIso: string;
  toIso: string;
};

function billPeriodEndIso(inv: Invoice): string {
  const to = inv.toDate != null ? String(inv.toDate).trim().slice(0, 10) : '';
  if (/^\d{4}-\d{2}-\d{2}$/.test(to)) return to;
  const from = inv.fromDate != null ? String(inv.fromDate).trim().slice(0, 10) : '';
  return /^\d{4}-\d{2}-\d{2}$/.test(from) ? from : '';
}

/**
 * When generating supporting documents at tax-invoice time, limit O&M 10-year aggregation to:
 * - the bill being processed, and
 * - earlier bills that already left performa (non-pending).
 *
 * Excludes later performa rows (e.g. month 5 while generating month 4) and other pending proforma bills.
 */
export function filterInvoicesForTaxInvoiceOmTenYear(
  invoices: Invoice[],
  anchor: TaxInvoiceOmTenYearAnchor
): Invoice[] {
  const anchorId = String(anchor.invoiceId || '').trim();
  const anchorEnd = String(anchor.toIso || anchor.fromIso || '').trim().slice(0, 10);
  if (!anchorId || !/^\d{4}-\d{2}-\d{2}$/.test(anchorEnd)) {
    return invoices;
  }

  return invoices.filter((inv) => {
    const id = String(inv.id || '');
    if (id === anchorId) return true;

    const invEnd = billPeriodEndIso(inv);
    if (invEnd && invEnd > anchorEnd) return false;

    if (String(inv.status || '').toLowerCase() === INVOICE_WORKFLOW_STATUS.PENDING) {
      return false;
    }

    return true;
  });
}
