// src/commands/woAddNote.js
import botClient from '../integrations/webex/botClient.js';
import { addWorkOrderNote } from '../integrations/serviceChannel/client.js';
import db from '../db/mappings.js';
import { logger } from '../utils/logger.js';
import { resolveDisplayName, resolveWoRoomContext } from '../utils/woRoomContext.js';
import { tryClaimBotMessage } from '../db/botMessageDedup.js';

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

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

  if (!noteText) {
    await bot.say('Usage: `/addNote your note text here` (WO space only).');
    return;
  }

  const ctx = await resolveWoRoomContext({ db, botClient, roomId, isGroup });
  if (!ctx.ok) {
    await bot.say(ctx.error);
    return;
  }

  const messageId = trigger.message?.id;
  try {
    const claimed = await tryClaimBotMessage(db, messageId, 'addNote');
    if (!claimed) {
      logger('wo:addNote', `Skipped duplicate /addNote for message ${messageId}`, 'info');
      return;
    }
  } catch (err) {
    logger('wo:addNote', `Dedup check failed: ${err.message}`, 'warn');
  }

  const displayName = await resolveDisplayName(botClient, trigger.personId);
  const scNote = `${displayName}: ${noteText}`;

  try {
    await addWorkOrderNote(ctx.workOrderId, scNote);
    logger('wo:addNote', `Posted note to SC WO ${ctx.workOrderId} by ${displayName}`);
    await bot.say(`Note added to the work order in ServiceChannel.`);
  } catch (err) {
    logger('wo:addNote', `Failed to post SC note for WO ${ctx.workOrderId}: ${err.message}`, 'error');
    await bot.say(`Could not add the note in ServiceChannel: ${err.message}`);
  }
}
