// src/commands/woApprove.js
// Manual trigger for posting the proposal approval package (markdown + card) in the current WO room.
// Useful for testing, re-sending, or if webhook was missed.

import botClient from '../integrations/webex/botClient.js';
import approvalService from '../services/approvalService.js';
import db from '../db/mappings.js';
import { getWorkOrderForNte } from '../integrations/serviceChannel/client.js';

export async function handleWoApprove(bot, trigger) {
  console.log('[WO-APPROVE] HANDLER ENTERED');

  let woId = null;

  if (trigger.message && trigger.message.roomType === 'group') {
    woId = await botClient.getWOByRoom(trigger.message.roomId);
  }

  if (!woId && trigger.args && trigger.args[0]) {
    woId = String(trigger.args[0]).replace(/\D/g, '');
  }

  if (!woId) {
    await bot.say('Could not determine Work Order from this space. Use `/woApprove 123456` or ensure you are in a ServChan WO room.');
    return;
  }

  const roomId = trigger.message ? trigger.message.roomId : null;
  if (!roomId) {
    await bot.say('No room context for card post.');
    return;
  }

  try {
    await bot.say(`Fetching proposals and building approval package for WO-${woId}...`);

    const woDetails = await getWorkOrderForNte(woId);
    if (!woDetails) {
      await bot.say(`Could not load WO-${woId} from ServiceChannel.`);
      return;
    }

    await approvalService.postApprovalPackage(botClient, roomId, woDetails, null, { skipDedup: true, db });

    await bot.say('Approval package posted (itemized summary + card). Use the card to approve.');
  } catch (err) {
    console.error('[WO-APPROVE] Error:', err);
    await bot.say(`Error preparing approval package for WO-${woId}: ${err.message}`);
  }
}
