// src/commands/woTrackStatus.js
import botClient from '../integrations/webex/botClient.js';
import db from '../db/mappings.js';
import { logger } from '../utils/logger.js';
import { resolveWoRoomContext } from '../utils/woRoomContext.js';
import {
  isFedExConfigured,
  isShipmentTrackingEnabled,
} from '../integrations/fedex/client.js';
import {
  pollShipmentsForWorkOrder,
  formatShipmentStatusMarkdown,
} from '../services/shipmentTrackingService.js';
import webexService from '../services/webexService.js';

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

  if (!isShipmentTrackingEnabled() || !isFedExConfigured()) {
    await bot.say('FedEx shipment tracking is not configured on this bot.');
    return;
  }

  const roomId = trigger.message?.roomId;
  const isGroup = trigger.message?.roomType === 'group';

  const ctx = await resolveWoRoomContext({ db, botClient, roomId, isGroup });
  if (!ctx.ok) {
    await bot.say(ctx.error);
    return;
  }

  await bot.say('Checking FedEx tracking status for this work order…');

  const result = await pollShipmentsForWorkOrder({
    db,
    webex: webexService,
    workOrderId: ctx.workOrderId,
  });

  if (result.skipped) {
    await bot.say('Tracking poll could not run.');
    return;
  }

  if (result.checked === 0) {
    await bot.say('No active FedEx shipments are registered for this work order.');
    return;
  }

  const lines = (result.shipments || []).map((s) => formatShipmentStatusMarkdown(s));
  const summary =
    result.checked === 1
      ? '1 shipment checked'
      : `${result.checked} shipments checked`;

  await bot.say({
    markdown:
      `**FedEx tracking refresh**\n\n` +
      `${lines.join('\n')}\n\n` +
      `_${summary}${result.delivered ? ` · ${result.delivered} newly delivered` : ''}_`,
  });
}
