// src/commands/woSummary.js
import botClient from '../integrations/webex/botClient.js';
import { logger } from '../utils/logger.js';
import {
  assertCollabSupportConfigured,
  fetchCollabMarkdown,
} from '../integrations/collabSupport/client.js';

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

  const args = trigger.args || [];

  let woId = (args[0] || '').trim();
  if (!woId && trigger.message?.roomType === 'group') {
    woId = await botClient.getWOByRoom(trigger.message.roomId);
  }

  if (!woId) {
    await bot.say('Please provide a valid work order number (e.g. `/woSummary 356369551`).');
    return;
  }

  try {
    assertCollabSupportConfigured();
  } catch {
    logger('wo:summary', 'CS_API_BASE not configured', 'warn');
    await bot.say('The work-order summary service is not configured on this bot (missing `CS_API_BASE`).');
    return;
  }

  try {
    const result = await fetchCollabMarkdown('/wosummary', { woId }, { logTag: 'wo:summary' });

    if (result.status === 400 || result.isUsageResponse) {
      await bot.say(`Invalid Work Order ID: **${woId}**.`);
      return;
    }
    if (!result.ok) {
      throw new Error(`HTTP ${result.status}`);
    }

    await bot.say({ markdown: result.markdown });
  } catch (err) {
    logger('wo:summary', `Failed for ${woId}: ${err.message}`, 'error');
    await bot.say(`Sorry, I couldn't fetch the summary for WO **${woId}** right now. (${err.message})`);
  }
}
