/**
 * ExpertVoice Order Reporter — Shopify Flow
 *
 * This integration uses two Flow actions:
 *   1. Run code  — filters the order and builds the request payload
 *   2. Send HTTP Request  — POSTs the payload to ExpertVoice
 *
 * ─── SETUP INSTRUCTIONS ──────────────────────────────────────────────────────
 *
 * STEP 1 — FILL IN YOUR CONFIGURATION
 *   Before doing anything in Shopify, fill in the two constants at the top
 *   of the CODE section below:
 *     REPORTING_ID  — your ExpertVoice Reporting ID
 *     PREFIXES      — the discount code prefix(es) ExpertVoice uses for your brand
 *
 * STEP 2 — CREATE THE WORKFLOW
 *   Shopify Admin → Apps → Flow → Create workflow
 *   Set the trigger to: "Order created"
 *
 * STEP 3 — ADD THE "RUN CODE" ACTION
 *   Click "+" → search "Run code" → select it.
 *   The editor has three tabs: Code, Input, and Output.
 *   Paste the contents of each labeled section below into the matching tab.
 *
 * STEP 4 — ADD A CONDITION
 *   After the Run code action, click "+" → add a "Condition".
 *   Set it to: Run code → shouldReport  is equal to  true
 *   This ensures the HTTP request only fires for qualifying orders.
 *
 * STEP 5 — ADD THE "SEND HTTP REQUEST" ACTION  (inside the true branch)
 *   Click "+" in the true branch → search "Send HTTP request" → select it.
 *
 *   a) Click "Import from cURL" and paste the following, then click Import:
 *
 *      curl -X POST https://www.expertvoice.com/pixel-gateway/ext/1.0/gateway \
 *        -H "Accept: application/json" \
 *        -H "Connection: keep-alive" \
 *        -H "Content-Type: application/json" \
 *        -H "sec-ch-ua-mobile: ?0" \
 *        -H "sec-ch-ua-platform: macOS" \
 *        -H "sec-ch-ua: Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"" \
 *        -H "sec-fetch-dest: empty" \
 *        -H "sec-fetch-mode: cors" \
 *        -H "sec-fetch-site: cross-site" \
 *        -H "x-codingscape-dev: 1" \
 *        -d '{}'
 *
 *   b) In the Body field, delete the placeholder '{}', click "Add variable",
 *      and select "payload" from the Run code action output.
 *
 * STEP 6 — SAVE & ENABLE
 *   Save the workflow and turn it on.
 *
 * STEP 7 — TEST
 *   Use Flow's "Test" button with an order that has a matching discount code.
 *   Confirm a 200 or 204 response is logged before enabling for live traffic.
 */


/* ═══════════════════════════════════════════════════════════════════════════
   INPUT  —  paste into the "Input" tab in the Run code action
   ═══════════════════════════════════════════════════════════════════════════

query {
  order {
    number
    currencyCode
    processedAt
    tags
    discountCodes
    customer { tags }
    totalDiscountsSet { presentmentMoney { amount } }
    totalShippingPriceSet { presentmentMoney { amount } }
    currentSubtotalPriceSet { presentmentMoney { amount } }
    currentTotalPriceSet { presentmentMoney { amount } }
    currentTotalTaxSet { presentmentMoney { amount } }
    shippingAddress {
      city
      countryCode
      zip
      provinceCode
    }
    lineItems {
      name
      sku
      quantity
      originalUnitPriceSet { presentmentMoney { amount } }
      product { legacyResourceId }
    }
  }
  shop { myshopifyDomain }
}

   ═══════════════════════════════════════════════════════════════════════════ */


/* ═══════════════════════════════════════════════════════════════════════════
   OUTPUT  —  paste into the "Output" tab in the Run code action
   ═══════════════════════════════════════════════════════════════════════════

type Output {
  shouldReport: Boolean!
  reason: String
  payload: String
}

   ═══════════════════════════════════════════════════════════════════════════ */


/* ═══════════════════════════════════════════════════════════════════════════
   CODE  —  paste into the "Code" tab in the Run code action
   ═══════════════════════════════════════════════════════════════════════════ */

// ─── Configuration ────────────────────────────────────────────────────────────

// Enter your ExpertVoice Reporting ID
const REPORTING_ID = 'exp-962-524057';

// Orders are only reported when at least one discount code, order tag, or
// customer tag starts with one of these prefixes (case-insensitive).
// Example: const PREFIXES = ['EV-', 'EXP-'];
const PREFIXES = ['EXPV'];

// ─── Helpers ─────────────────────────────────────────────────────────────────

function hasMatchingPrefix(codes, prefixes) {
  return codes.some(code =>
    code && prefixes.some(p => code.toLowerCase().startsWith(p.toLowerCase()))
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────

export default function main({ order, shop }) {
  const [, PIXEL_ID, ORG_ID] = REPORTING_ID.split('-');

  const discountCodes = (order.discountCodes || []).filter(Boolean);
  const orderTags     = order.tags           || [];
  const customerTags  = order.customer?.tags || [];
  const allCodes      = [...discountCodes, ...orderTags, ...customerTags];

  if (!hasMatchingPrefix(allCodes, PREFIXES)) {
    return { shouldReport: false, reason: 'No matching prefix — order not reported.', payload: null };
  }

  const products = (order.lineItems || []).map(item => ({
    id:       String(item.product?.legacyResourceId || ''),
    name:     item.name || '',
    sku:      item.sku  || '',
    upc:      '',
    price:    item.originalUnitPriceSet?.presentmentMoney?.amount,
    quantity: item.quantity
  }));

  const subtotal = order.currentSubtotalPriceSet?.presentmentMoney?.amount || '0.00';
  const discount = order.totalDiscountsSet?.presentmentMoney?.amount       || '0.00';

  const payload = {
    action:  'REDIRECT-ORDERPLACED',
    appName: 'external-redirect',
    data: {
      custom:    {},
      eventDate: String(Date.parse(order.processedAt)),
      order: {
        code:          allCodes,
        currency:      order.currencyCode,
        discount,
        id:            order.number,
        msrp_subtotal: (parseFloat(subtotal) + parseFloat(discount)).toFixed(2),
        shipping:      order.totalShippingPriceSet?.presentmentMoney?.amount,
        shipping_address: {
          city:        order.shippingAddress?.city         || '',
          country:     order.shippingAddress?.countryCode  || '',
          postal_code: order.shippingAddress?.zip          || '',
          state:       order.shippingAddress?.provinceCode || ''
        },
        subtotal,
        total: order.currentTotalPriceSet?.presentmentMoney?.amount,
        tax:   order.currentTotalTaxSet?.presentmentMoney?.amount
      },
      orgId:        ORG_ID,
      pageCategory: 'order-app-shopify',
      pixelId:      PIXEL_ID,
      products,
      version:      '3.0'
    },
    mfgId:     ORG_ID,
    referrer:  null,
    url:       shop.myshopifyDomain,
    userAgent: '',
    version:   1
  };

  return { shouldReport: true, reason: null, payload: JSON.stringify(payload) };
}
