// src/commands/woTrackTest.js
// One-off FedEx API lookup — does not persist to shipment_tracking.

import { logger } from '../utils/logger.js';
import { isFedExConfigured, trackByNumbers, formatFedExStatusLine } from '../integrations/fedex/client.js';
import { parseFedExTrackingNumbers } from '../services/shipmentTrackingService.js';

const PLAIN_NUMBER_RE = /^\d{12,22}$/;

function parseTrackingArgs(args = []) {
  const raw = args.join(' ').trim();
  if (!raw) return [];

  const fromFedExPrefix = parseFedExTrackingNumbers(`FEDEX ${raw}`);
  if (fromFedExPrefix.length) return fromFedExPrefix;

  const found = new Set();
  for (const part of raw.split(/[,\s]+/)) {
    const num = part.trim().replace(/^fedex\s*/i, '');
    if (PLAIN_NUMBER_RE.test(num)) found.add(num);
  }
  return [...found];
}

function formatResult(result) {
  const url = `https://www.fedex.com/fedextrack/?trknbr=${encodeURIComponent(result.trackingNumber)}`;
  if (!result.ok) {
    return `- **[${result.trackingNumber}](${url})** — API error: ${result.error}`;
  }

  return `- **[${result.trackingNumber}](${url})** — ${formatFedExStatusLine(result)}`;
}

export async function handleWoTrackTest(bot, trigger) {
  logger('wo:trackTest', 'HANDLER ENTERED');

  if (!isFedExConfigured()) {
    await bot.say('FedEx API is not configured (`FEDEX_CLIENT_ID`, `FEDEX_CLIENT_SECRET`, `FEDEX_API_BASE`).');
    return;
  }

  const numbers = parseTrackingArgs(trigger.args);
  if (!numbers.length) {
    await bot.say(
      'Usage: `/trackTest 876239420601` or `/trackTest FEDEX 876239420601, 876239420612`\n\n' +
        'Looks up status via the FedEx API only — nothing is saved to ServChan.'
    );
    return;
  }

  if (numbers.length > 30) {
    await bot.say('FedEx allows up to 30 tracking numbers per request. Please pass fewer numbers.');
    return;
  }

  await bot.say(`Querying FedEx for **${numbers.length}** tracking number(s)…`);

  try {
    const results = await trackByNumbers(numbers);
    const lines = numbers.map((n) => formatResult(results.get(n) || { trackingNumber: n, ok: false, error: 'No response' }));
    const apiBase = process.env.FEDEX_API_BASE || 'https://apis.fedex.com';

    await bot.say({
      markdown:
        `**FedEx API test** (\`${apiBase}\`)\n\n` +
        `${lines.join('\n')}\n\n` +
        `_Not stored — use SC notes or /trackStatus for ongoing WO tracking._`,
    });
    logger('wo:trackTest', `Looked up ${numbers.length} number(s): ${numbers.join(', ')}`);
  } catch (err) {
    logger('wo:trackTest', `FedEx API error: ${err.message}`, 'error');
    await bot.say(`FedEx API request failed: ${err.message}`);
  }
}
