// src/commands/woAttach.js
import botClient from '../integrations/webex/botClient.js';
import db from '../db/mappings.js';
import { logger } from '../utils/logger.js';
import { uploadFilesFromTrigger } from '../services/workOrderUploadService.js';

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

  const isGroup = trigger.message?.roomType === 'group';
  const caption = (trigger.args || []).join(' ').trim();

  if (!isGroup) {
    await bot.say('Use `/attach` or `/upload` in a ServChan work order space with a file attached to the message.');
    return;
  }

  try {
    const result = await uploadFilesFromTrigger({ db, botClient, trigger, caption });

    if (!result.ok) {
      if (result.error) await bot.say(result.error);
      return;
    }

    const names = result.uploaded.map((u) => u.name);
    let msg;
    if (names.length === 1) {
      msg = `Uploaded **${names[0]}** to ServiceChannel.`;
    } else {
      msg = `Uploaded **${names.length}** file(s) to ServiceChannel: ${names.map((n) => `**${n}**`).join(', ')}.`;
    }
    if (result.captionPosted) {
      msg += ' Caption added as a note.';
    }

    await bot.say(msg);
  } catch (err) {
    logger('wo:attach', `Upload failed: ${err.message}`, 'error');
    await bot.say(`Could not upload to ServiceChannel: ${err.message}`);
  }
}
