function escapeXml(value) {
    if (value === null || value === undefined) return '';
    return String(value)
        .replace(/&/g, '&amp;') // Note: & doit être échappé en premier
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&apos;'); // Ligne corrigée
}
class EdecGeneratorExport {
generateExport(data) {
const now = new Date().toISOString().replace('T', ' ').replace('Z', ' UTC');
const lang = (data.language || 'fr').toLowerCase();
    // Consignor (expéditeur CH) - équivalent importateur
    const consignorName = escapeXml(data.consignor_name || data.user_name);
    const consignorStreet = escapeXml(data.consignor_address || data.user_address);
    const consignorZip = escapeXml(data.consignor_zip || data.user_zip);
    const consignorCity = escapeXml(data.consignor_city || data.user_city);
    const consignorCountry = 'CH';
    const consignorIde = escapeXml(data.consignor_ide || data.user_ide || 'CHE222251936');

    // Consignee (destinataire étranger)
    const consigneeName = escapeXml(data.consignee_name);
    const consigneeStreet = escapeXml(data.consignee_address);
    const consigneeZip = escapeXml(data.consignee_zip);
    const consigneeCity = escapeXml(data.consignee_city);
    const consigneeCountry = escapeXml(data.destination_country);

    // Declarant
    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 declarantCountry = escapeXml(data.declarant_country || consigneeCountry);

    const description = escapeXml(`${data.brand} ${data.model} ${data.year}`.trim());
    const commodityCode = escapeXml(data.commodity_code);
    const statisticalCode = escapeXml(data.statistical_key);
    const vin = escapeXml(data.vin);
    const brandCode = escapeXml(data.brand_code);
    const matriculationNumber = escapeXml(data.matriculation_number);

    const grossMass = Math.round(Number(data.weight_total || 0));
    const statisticalValue = Math.round(Number(data.statistical_value || data.purchase_price || 0));

    // Construction des détails du véhicule
    let goodsItemDetailsXml = '';
    if (brandCode || vin || matriculationNumber) {
        goodsItemDetailsXml = `
    <goodsItemDetails>
      <goodsItemDetail>`;
        
        if (brandCode) {
            goodsItemDetailsXml += `
        <GoodsItemDetail>
          <name>1</name>
          <value>${brandCode}</value>
        </GoodsItemDetail>`;
        }
        
        if (vin) {
            goodsItemDetailsXml += `
        <GoodsItemDetail>
          <name>2</name>
          <value>${vin}</value>
        </GoodsItemDetail>`;
        }
        
        if (matriculationNumber) {
            goodsItemDetailsXml += `
        <GoodsItemDetail>
          <name>3</name>
          <value>${matriculationNumber}</value>
        </GoodsItemDetail>`;
        }
        
        goodsItemDetailsXml += `
      </goodsItemDetail>
    </goodsItemDetails>`;
    }

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<EdecWeb version="4.0" createdDate="${now}">
  <goodsDeclarationType>
    <serviceType>2</serviceType>
    <declarationType>1</declarationType>
    <language>${lang}</language>
    <deliveryDestination>${consigneeCountry}</deliveryDestination>
    <transportMeans>
      <transportMode>9</transportMode>
      <transportationNumber></transportationNumber>
    </transportMeans>
    <transportInContainer>0</transportInContainer>
    <previousDocument/>
    <consignor>
      <name>${consignorName}</name>
      ${consignorStreet ? `<street>${consignorStreet}</street>` : ''}
      <postalCode>${consignorZip}</postalCode>
      <city>${consignorCity}</city>
      <country>${consignorCountry}</country>
      <traderIdentificationNumber>${consignorIde}</traderIdentificationNumber>
    </consignor>
    <consignee>
      <name>${consigneeName}</name>
      ${consigneeStreet ? `<street>${consigneeStreet}</street>` : ''}
      <postalCode>${consigneeZip}</postalCode>
      <city>${consigneeCity}</city>
      <country>${consigneeCountry}</country>
    </consignee>
    <declarant>
      ${declarantIde ? `<traderIdentificationNumber>${declarantIde}</traderIdentificationNumber>` : '<traderIdentificationNumber></traderIdentificationNumber>'}
      <name>${declarantName}</name>
      ${declarantStreet ? `<street>${declarantStreet}</street>` : ''}
      <postalCode>${declarantZip}</postalCode>
      <city>${declarantCity}</city>
      <country>${declarantCountry}</country>
    </declarant>
    <business>
      <vatNumber> </vatNumber>
      <vatSuffix>0</vatSuffix>
      <invoiceCurrencyType>1</invoiceCurrencyType>
    </business>
    <goodsItem>
      <GoodsItemType>
        <traderItemID>0</traderItemID>
        <description>${description}</description>
        <commodityCode>${commodityCode}</commodityCode>
        <statisticalCode>${statisticalCode}</statisticalCode>
        ${grossMass > 0 ? `<grossMass>${grossMass}</grossMass>` : ''}
        ${grossMass > 0 ? `<netMass>${grossMass}</netMass>` : ''}
        <additionalUnit>1</additionalUnit>
        <permitObligation>2</permitObligation>
        <nonCustomsLawObligation>2</nonCustomsLawObligation>
        <statistic>
          <customsClearanceType>1</customsClearanceType>
          <commercialGood>1</commercialGood>
          ${statisticalValue > 0 ? `<statisticalValue>${statisticalValue}</statisticalValue>` : ''}
          <repair>0</repair>
        </statistic>
        ${goodsItemDetailsXml}
        <packaging>
          <PackagingType>
            <packagingType>VN</packagingType>
            <quantity>1</quantity>
            <packagingReferenceNumber>${description}</packagingReferenceNumber>
          </PackagingType>
        </packaging>
      </GoodsItemType>
    </goodsItem>
  </goodsDeclarationType>
</EdecWeb>`;
        return xml;
    }
}
module.exports = new EdecGeneratorExport();
