// src/commands/woHistory.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 handleWoHistory(bot, trigger) {
  logger('wo:history', 'HANDLER ENTERED');

  const args = trigger.args || [];
  const mode = args[1]?.toLowerCase() === 'detailed' ? 'detailed' : 'summary';

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

  if (!storeNum || !/^\d{2,4}$/.test(storeNum)) {
    await bot.say('Please provide a 2–4 digit store number after `/woHistory`\n(e.g. `/woHistory 2477 [detailed]`).');
    return;
  }

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

  const params = { storeNum };
  if (mode === 'detailed') params.mode = 'detailed';

  try {
    const result = await fetchCollabMarkdown('/wohistory', params, { logTag: 'wo:history' });

    if (result.status === 400 || result.isUsageResponse) {
      await bot.say('Invalid store number format. Please use 2-4 digits.');
      return;
    }
    if (!result.ok) {
      throw new Error(`HTTP ${result.status}`);
    }

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