// src/commands/avStatus.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 handleAvStatus(bot, trigger) {
  logger('av:status', '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 `/avStatus`\n(e.g. `/avStatus 2477 [detailed]`).');
    return;
  }

  try {
    assertCollabSupportConfigured();
  } catch {
    logger('av:status', 'CS_API_BASE not configured', 'warn');
    await bot.say('The AV status 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('/avStatus', params, { logTag: 'av:status' });

    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('av:status', `Failed for ${storeNum}: ${err.message}`, 'error');
    await bot.say(`Sorry, I couldn't fetch device status for store **${storeNum}** right now. (${err.message})`);
  }
}
