function escapeXml(value) {
  if (value === null || value === undefined) return '';
  return String(value)
    .replace(/&/g, '&amp;').replace(/</g, '&lt;')
    .replace(/>/g, '&gt;').replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

// invoiceCurrencyType mapping:
// 1=CHF, 2=EUR, 3=USD, 4=Autre monnaie UE, 5=Autre monnaie
function mapInvoiceCurrencyType(currency) {
  if (currency === 'CHF') return 1;
  if (currency === 'EUR') return 2;
  if (currency === 'USD') return 3;

  // Liste des pays de l'UE qui n'utilisent pas l'Euro (BGN, CZK, DKK, HUF, PLN, RON, SEK)
  const euNonEuroCurrencies = ['BGN', 'CZK', 'DKK', 'HUF', 'PLN', 'RON', 'SEK'];
  if (euNonEuroCurrencies.includes(currency)) {
    return 4; // Autre monnaie UE
  }

  return 5; // Autre monnaie
}

class EdecGeneratorImport {
  generateImport(data) {
    // CORRECTION: Remplace 'T' par un espace et 'Z' par ' UTC' pour le format e-dec (YYYY-MM-DD HH:mm:ss.sss UTC)
    const now = new Date().toISOString().replace('T', ' ').replace('Z', ' UTC');
    
    const lang = (data.language || 'fr').toLowerCase();
    const dispatchCountry = data.dispatch_country;
    const transportMode = data.transport_mode; 
    
    // Le nom (raison sociale ou Prénom Nom) est désormais formaté par le controller client
    const importerName = escapeXml(data.user_name);
    const importerStreet = escapeXml(data.user_address);
    const importerZip = escapeXml(data.user_zip);
    const importerCity = escapeXml(data.user_city);
    const importerCountry = 'CH';
    const ide = escapeXml(data.user_ide || 'CHE222251936'); // Particulier par défaut

    const consigneeName = escapeXml(data.consignee_name || data.user_name);
    const consigneeStreet = escapeXml(data.consignee_address || data.user_address);
    const consigneeZip = escapeXml(data.consignee_zip || data.user_zip);
    const consigneeCity = escapeXml(data.consignee_city || data.user_city);
    const consigneeIde = escapeXml(data.consignee_ide || ide);

    const declarantName = escapeXml(data.declarant_name || data.user_name);
    const declarantStreet = escapeXml(data.declarant_address || data.user_address);
    const declarantZip = escapeXml(data.declarant_zip || data.user_zip);
    const declarantCity = escapeXml(data.declarant_city || data.user_city);
    const declarantIde = escapeXml(data.declarant_ide);

    const description = escapeXml(`${data.brand} ${data.model} ${data.year}`.trim());
    const commodityCode = escapeXml(data.commodity_code); 
    const statisticalCode = escapeXml(data.statistical_key); 
    
    // Les masses doivent être des nombres entiers (arrondi par précaution)
    const grossMass = Math.round(Number(data.weight_empty)); // Mettre le poids a vide meme dans le poids brut Math.round(Number(data.weight_total || 0));
    const netMass = Math.round(Number(data.weight_empty));

    // Correction: La valeur statistique et la base TVA sont arrondies à l'ENTIER.
    // statisticalValue (Prix d'achat hors coûts annexes)
    const statisticalValue = Math.round(Number(data.statistical_value_chf || data.statistical_value || 0)); 
    // vatValue (Prix d'achat + coûts annexes)
    const vatValue = Math.round(Number(data.vat_value_chf || data.vatValue || statisticalValue));

    const vin = escapeXml(data.vin || '');
    const brandCode = escapeXml(data.brand_code || '');

    const originCountry = escapeXml(data.origin_country || data.originCountry || dispatchCountry || 'FR');
    const preference = 0; // pas de tarif préférentiel par défaut

    // TVA code: 1 normal, 3 déménagement
    const vatCode = data.is_relocation ? '3' : '1';

    // Additional tax (IVA) RG 660: key 001 (assujetti) ou 002 (exonéré)
    const additionalTaxKey = data.is_iva_exempt ? '002' : '001';
    // Assure que la quantité pour la taxe additionnelle est un entier
    const additionalTaxQty = statisticalValue; 

    // Utilisation de data.purchase_currency pour déduire le type de monnaie
    const invoiceCurrencyType = mapInvoiceCurrencyType(data.purchase_currency);
    
    // Construction des détails de l'article de marchandise (VIN et Brand Code)
    let goodsItemDetailsXml = '';
    if (vin || brandCode) {
        goodsItemDetailsXml = `
        <goodsItemDetails>
          <goodsItemDetail>
            <GoodsItemDetail>
              <name>2</name>
              <value>${vin}</value>
            </GoodsItemDetail>
            ${brandCode ? `
            <GoodsItemDetail>
              <name>1</name>
              <value>${brandCode}</value>
            </GoodsItemDetail>` : ''}
          </goodsItemDetail>
        </goodsItemDetails>`;
    }

    // Ajout de l'entête XML et utilisation de la variable now corrigée
    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<EdecWeb version="4.0" createdDate="${now}">
  <goodsDeclarationType>
    <serviceType>1</serviceType>
    <declarationType>1</declarationType>
    <language>${lang}</language>
    <dispatchCountry>${dispatchCountry}</dispatchCountry>
    <transportMeans>
      <transportMode>${transportMode}</transportMode>
      <transportationNumber></transportationNumber>
    </transportMeans>
    <transportInContainer>0</transportInContainer>
    <previousDocument/>
    <importer>
      <name>${importerName}</name>
      ${importerStreet ? `<street>${importerStreet}</street>` : ''}
      <postalCode>${importerZip}</postalCode>
      <city>${importerCity}</city>
      <country>${importerCountry}</country>
      <traderIdentificationNumber>${ide}</traderIdentificationNumber>
    </importer>
    <consignee>
      <name>${consigneeName}</name>
      ${consigneeStreet ? `<street>${consigneeStreet}</street>` : ''}
      <postalCode>${consigneeZip}</postalCode>
      <city>${consigneeCity}</city>
      <country>${importerCountry}</country>
      <traderIdentificationNumber>${consigneeIde}</traderIdentificationNumber>
    </consignee>
    <declarant>
      ${declarantIde ? `<traderIdentificationNumber>${declarantIde}</traderIdentificationNumber>` : '<traderIdentificationNumber></traderIdentificationNumber>'}
      <name>${declarantName}</name>
      ${declarantStreet ? `<street>${declarantStreet}</street>` : ''}
      <postalCode>${declarantZip}</postalCode>
      <city>${declarantCity}</city>
      <country>${importerCountry}</country>
    </declarant>
    <business>
      <customsAccount>0</customsAccount>
      <vatAccount>0</vatAccount>
      <vatSuffix>0</vatSuffix>
      <invoiceCurrencyType>${invoiceCurrencyType}</invoiceCurrencyType>
    </business>
    <goodsItem>
      <GoodsItemType>
        <traderItemID>0</traderItemID>
        <description>${description}</description>
        <commodityCode>${commodityCode}</commodityCode>
        <statisticalCode>${statisticalCode}</statisticalCode>
        <grossMass>${grossMass}</grossMass>
        <netMass>${netMass}</netMass>
        <additionalUnit>1</additionalUnit>
        <permitObligation>0</permitObligation>
        <nonCustomsLawObligation>2</nonCustomsLawObligation>
        <statistic>
          <customsClearanceType>1</customsClearanceType>
          <commercialGood>1</commercialGood>
          <statisticalValue>${statisticalValue}</statisticalValue>
          <repair>0</repair>
        </statistic>
        <origin>
          <originCountry>${originCountry}</originCountry>
          <preference>${preference}</preference>
        </origin>
        ${goodsItemDetailsXml}
        <packaging>
          <PackagingType>
            <packagingType>VN</packagingType>
            <quantity>1</quantity>
            <packagingReferenceNumber>${description}</packagingReferenceNumber>
          </PackagingType>
        </packaging>
        <valuation>
          <netDuty>0</netDuty>
          <vatValue>${vatValue}</vatValue>
          <vatCode>${vatCode}</vatCode>
        </valuation>
        <additionalTax>
          <AdditionalTaxType>
            <type>660</type>
            <key>${additionalTaxKey}</key>
            <quantity>${additionalTaxQty}</quantity>
          </AdditionalTaxType>
        </additionalTax>
      </GoodsItemType>
    </goodsItem>
  </goodsDeclarationType>
</EdecWeb>`;

    return xml;
  }
}

module.exports = new EdecGeneratorImport();

