// src/commands/woAttachments.js
import botClient from '../integrations/webex/botClient.js';
import webexService from '../services/webexService.js';
import db from '../db/mappings.js';
import { logger } from '../utils/logger.js';
import { postWorkOrderAttachments } from '../services/attachmentService.js';

function lookupWorkOrderIdByRoom(roomId) {
  return new Promise((resolve, reject) => {
    db.get(
      'SELECT workOrderId FROM mappings WHERE roomId = ?',
      [roomId],
      (err, row) => (err ? reject(err) : resolve(row?.workOrderId ?? null))
    );
  });
}

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

  const args = trigger.args || [];
  const roomId = trigger.message?.roomId;

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

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

  if (!roomId) {
    await bot.say('Could not determine the current Webex room.');
    return;
  }

  let workOrderId = woNumber;
  try {
    const mappedId = await lookupWorkOrderIdByRoom(roomId);
    if (mappedId) workOrderId = mappedId;
  } catch (err) {
    logger('wo:attachments', `Room mapping lookup failed: ${err.message}`, 'warn');
  }

  try {
    await bot.say({ markdown: `🔍 Looking up attachments for work order **${woNumber}**...` });

    const { posted, skipped, links = 0 } = await postWorkOrderAttachments({
      db,
      webex: webexService,
      roomId,
      workOrderId,
      woNumber,
      skipDedup: true,
    });

    if (posted === 0 && skipped === 0) {
      await bot.say({ markdown: `No attachments found for WO **${woNumber}**.` });
      return;
    }

    const fileCount = posted - links;
    let summary = `✅ Finished for WO **${woNumber}**: **${fileCount}** file(s) uploaded`;
    if (links > 0) {
      summary += `, **${links}** link-only (HEIC conversion unavailable — rebuild container with \`docker compose down -v && docker compose up --build\`)`;
    }
    if (skipped > 0) summary += `, **${skipped}** skipped`;
    summary += '.';
    await bot.say({ markdown: summary });
  } catch (err) {
    logger('wo:attachments', `Error for WO ${woNumber}: ${err.message}`, 'error');
    await bot.say(`❌ Error fetching attachments for WO **${woNumber}**: ${err.message}`);
  }
}
