'use strict';

/**
 * COD (cash-on-delivery) detection + amount/currency parse for a Shoptet
 * order-detail document.
 *
 * Injected into the Shoptet page context via webContents.executeJavaScript,
 * so this is a STRING snippet interpolated into a larger `src` template — NOT
 * a require()-able function (same pattern as SHIPPING_MODAL_SNIPPET).
 *
 * Single source of truth shared by:
 *   - shipment-flow.js   — create-time parser (single + bulk create)
 *   - shoptet-bridge.js  — bulk wizard preflight scan
 *
 * Contract at the injection site (must be in scope):
 *   - `doc`    — the parsed order-detail Document (DOMParser output).
 *   - `result` — object that receives result.codAmount (Number) and
 *                result.codCurrency ('CZK' | 'EUR' | 'UAH' | 'USD' | null).
 *
 * Detection: Shoptet's invoice "Payment form" codebook is GLOBAL and stable —
 * the SELECTED option's value "1" = Dobírkou/Dobierkou (COD), independent of
 * e-shop language or a merchant renaming / deleting+re-adding the method (that
 * changes the unstable per-eshop method id; an order keys on the billing TYPE,
 * which the detail does NOT expose as an id). Read ONLY the selected option —
 * "Dobírkou" is an unselected <option> on every order, so a free-text scan
 * would false-positive every order as COD.
 *
 * Amount + currency: the order total incl. VAT ("Price to pay"), NOT the
 * payment-method row price (the COD surcharge, often 0 Kč). The COD total
 * label carries the amount AND its currency together (e.g. "123,45 €"), so we
 * parse both — the currency is normalized to an ISO 4217 code for the BE.
 */
const COD_DETECT_SNIPPET = `
  {
    const codSel = doc.querySelector('select[name="invoiceBillingMethodId"]');
    const codOpt = codSel
      ? (codSel.querySelector('option[selected]')
         || (codSel.selectedIndex >= 0 ? codSel.options[codSel.selectedIndex] : null))
      : null;
    const isCodOrder = !!codOpt && (
      (codOpt.value || '').trim() === '1'
      || /Dob[\\u00edi]rk/i.test(codOpt.textContent || '')
    );
    if (isCodOrder) {
      const codTotalEl = doc.querySelector('[data-testid="textTotalPriceWithVat"]')
        || doc.querySelector('[data-testid="orderTotalPrice"]')
        || doc.querySelector('[data-testid="totalPrice"]');
      const codMatch = codTotalEl
        ? (codTotalEl.textContent || '').match(/(\\d[\\d \\u00a0.]*[.,]?\\d*)\\s*(K\\u010d|CZK|EUR|\\u20ac|UAH|\\u20b4|USD|\\$)/i)
        : null;
      if (codMatch) {
        result.codAmount = parseFloat(codMatch[1].replace(/[ \\u00a0]/g, '').replace(/\\.(?=\\d{3}(?:\\D|$))/g, '').replace(',', '.'));
        const codCur = codMatch[2];
        result.codCurrency = /K\\u010d|CZK/i.test(codCur) ? 'CZK'
          : /EUR|\\u20ac/i.test(codCur) ? 'EUR'
          : /UAH|\\u20b4/i.test(codCur) ? 'UAH'
          : /USD|\\$/i.test(codCur) ? 'USD' : null;
      }
    }
  }
`;

module.exports = { COD_DETECT_SNIPPET };
