/**
 * src/integrations/zatca/ubl.ts
 * UBL 2.1 invoice XML generator (Phase-1 simplified tax invoice).
 *
 * This skeleton emits the structural document ZATCA's compliance and
 * clearance APIs expect. Phase-1 does not require the cryptographic
 * stamp / digital signature — those go inline as ds:Signature children
 * once the signing module lands. Until then we emit unsigned XML and
 * persist the raw document so it can be re-signed and re-submitted later
 * without a schema migration.
 */
export function computeTotals(items) {
    let subtotal = 0;
    let vatTotal = 0;
    for (const it of items) {
        const line = it.quantity * it.unitPrice;
        subtotal += line;
        vatTotal += line * (it.vatRate / 100);
    }
    return {
        subtotal: round2(subtotal),
        vatTotal: round2(vatTotal),
        total: round2(subtotal + vatTotal),
    };
}
function round2(n) {
    return Math.round(n * 100) / 100;
}
function escapeXml(s) {
    return s
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&apos;');
}
/** Render a UBL 2.1 invoice XML document. */
export function renderUblInvoice(input) {
    const totals = computeTotals(input.items);
    const typeCode = input.invoiceType === 'simplified' ? '388' : '380';
    const cur = escapeXml(input.currency);
    const lines = input.items.map((it, idx) => {
        const line = round2(it.quantity * it.unitPrice);
        const lineVat = round2(line * (it.vatRate / 100));
        return `
  <cac:InvoiceLine>
    <cbc:ID>${idx + 1}</cbc:ID>
    <cbc:InvoicedQuantity unitCode="EA">${it.quantity}</cbc:InvoicedQuantity>
    <cbc:LineExtensionAmount currencyID="${cur}">${line.toFixed(2)}</cbc:LineExtensionAmount>
    <cac:TaxTotal>
      <cbc:TaxAmount currencyID="${cur}">${lineVat.toFixed(2)}</cbc:TaxAmount>
      <cbc:RoundingAmount currencyID="${cur}">${(line + lineVat).toFixed(2)}</cbc:RoundingAmount>
    </cac:TaxTotal>
    <cac:Item>
      <cbc:Name>${escapeXml(it.description)}</cbc:Name>
      <cac:ClassifiedTaxCategory>
        <cbc:ID>S</cbc:ID>
        <cbc:Percent>${it.vatRate.toFixed(2)}</cbc:Percent>
        <cac:TaxScheme><cbc:ID>VAT</cbc:ID></cac:TaxScheme>
      </cac:ClassifiedTaxCategory>
    </cac:Item>
    <cac:Price>
      <cbc:PriceAmount currencyID="${cur}">${it.unitPrice.toFixed(2)}</cbc:PriceAmount>
    </cac:Price>
  </cac:InvoiceLine>`;
    }).join('');
    const buyerBlock = input.buyer.vatNumber
        ? `
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>${escapeXml(input.buyer.vatNumber)}</cbc:CompanyID>
        <cac:TaxScheme><cbc:ID>VAT</cbc:ID></cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>${escapeXml(input.buyer.name)}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingCustomerParty>`
        : `
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>${escapeXml(input.buyer.name)}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingCustomerParty>`;
    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
         xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
         xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
         xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>${escapeXml(input.invoiceNumber)}</cbc:ID>
  <cbc:UUID>${escapeXml(input.invoiceUuid)}</cbc:UUID>
  <cbc:IssueDate>${input.issuedAt.slice(0, 10)}</cbc:IssueDate>
  <cbc:IssueTime>${input.issuedAt.slice(11, 19)}</cbc:IssueTime>
  <cbc:InvoiceTypeCode name="0200000">${typeCode}</cbc:InvoiceTypeCode>
  <cbc:DocumentCurrencyCode>${cur}</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>${cur}</cbc:TaxCurrencyCode>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>${escapeXml(input.seller.vatNumber)}</cbc:CompanyID>
        <cac:TaxScheme><cbc:ID>VAT</cbc:ID></cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>${escapeXml(input.seller.name)}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>${buyerBlock}
  <cac:TaxTotal>
    <cbc:TaxAmount currencyID="${cur}">${totals.vatTotal.toFixed(2)}</cbc:TaxAmount>
  </cac:TaxTotal>
  <cac:LegalMonetaryTotal>
    <cbc:LineExtensionAmount currencyID="${cur}">${totals.subtotal.toFixed(2)}</cbc:LineExtensionAmount>
    <cbc:TaxExclusiveAmount currencyID="${cur}">${totals.subtotal.toFixed(2)}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="${cur}">${totals.total.toFixed(2)}</cbc:TaxInclusiveAmount>
    <cbc:PayableAmount currencyID="${cur}">${totals.total.toFixed(2)}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>${lines}
</Invoice>`;
    return { xml, totals };
}
//# sourceMappingURL=ubl.js.map