/**
 * Adaptive Card flow for /createWO — create ServiceChannel work orders from DM.
 */

import { logger } from '../utils/logger.js';
import {
  buildCreateWorkOrderPayload,
  createWorkOrder,
  resolveCreateContractInfo,
} from '../integrations/serviceChannel/client.js';
import {
  getWorkOrderCreateConfig,
  isPersonAllowedToCreateWorkOrder,
  isWorkOrderCreateEnabled,
} from '../config/workOrderCreateConfig.js';
import webexService from './webexService.js';

const STORE_RE = /^\d{1,6}$/;

function _choiceSet(id, label, choices, defaultValue) {
  const items = (choices || []).map((value) => ({
    title: value,
    value,
  }));

  if (!items.length) {
    return {
      type: 'Input.Text',
      id,
      label,
      value: defaultValue || '',
      placeholder: label,
    };
  }

  return {
    type: 'Input.ChoiceSet',
    id,
    label,
    value: defaultValue || items[0].value,
    choices: items,
    style: 'compact',
  };
}

export function buildCreateWorkOrderAdaptiveCard(config = getWorkOrderCreateConfig()) {
  const body = [
    {
      type: 'TextBlock',
      text: 'Create ServiceChannel Work Order',
      size: 'medium',
      weight: 'bolder',
    },
    {
      type: 'TextBlock',
      text:
        `**${config.tradeName}** · **${config.providerName}** · ` +
        `NTE **$${Number(config.defaultNte).toFixed(2)}**`,
      isSubtle: true,
      wrap: true,
    },
    {
      type: 'Input.Text',
      id: 'storeId',
      label: 'Store number (short form OK — normalized to 6 digits)',
      placeholder: 'e.g. 305 or 000305',
      isRequired: true,
      maxLength: 6,
    },
    {
      type: 'Input.Text',
      id: 'description',
      label: 'Problem description',
      placeholder: 'Describe the AV issue…',
      isMultiline: true,
      isRequired: true,
    },
    _choiceSet('category', 'Category', config.categories, config.defaultCategory),
    _choiceSet('priority', 'Priority', config.priorities, config.defaultPriority),
  ];

  if (config.problemCodes.length) {
    body.push(_choiceSet('problemCode', 'Problem code', config.problemCodes, config.problemCodes[0]));
  } else {
    body.push({
      type: 'Input.Text',
      id: 'problemCode',
      label: config.requireIssueList ? 'Problem code (required)' : 'Problem code (optional)',
      placeholder: 'e.g. Display not working',
      isRequired: config.requireIssueList,
    });
  }

  body.push(
    {
      type: 'Input.Number',
      id: 'nte',
      label: 'NTE (max spend)',
      value: config.defaultNte,
      min: 0,
    },
    {
      type: 'TextBlock',
      text: 'After submit, ServChan creates the WO in ServiceChannel. The Webex group space appears automatically when the WorkOrderCreated webhook arrives.',
      size: 'small',
      isSubtle: true,
      wrap: true,
    }
  );

  return {
    $schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
    type: 'AdaptiveCard',
    version: '1.3',
    body,
    actions: [
      {
        type: 'Action.Submit',
        title: 'Create work order',
        style: 'positive',
        data: { action: 'createWorkOrder' },
      },
      {
        type: 'Action.Submit',
        title: 'Cancel',
        data: { action: 'dismissCreateWoCard' },
      },
    ],
  };
}

async function _removeCardMessage(bot, action) {
  const messageId = action?.messageId;
  if (!messageId) return;

  if (typeof bot?.censor === 'function') {
    try {
      await bot.censor(messageId);
      return;
    } catch (err) {
      logger('woCreate:submit', `bot.censor failed for ${messageId}: ${err.message}`, 'warn');
    }
  }

  try {
    const botClientMod = await import('../integrations/webex/botClient.js');
    await botClientMod.default.deleteMessage(messageId);
  } catch (err) {
    logger('woCreate:submit', `Could not delete card ${messageId}: ${err.message}`, 'warn');
  }
}

export async function postCreateWorkOrderCard(bot, trigger) {
  if (!isWorkOrderCreateEnabled()) {
    await bot.say('Work order creation is disabled on this bot (`SC_CREATE_ENABLED=false`).');
    return;
  }

  const personId = trigger?.message?.personId || trigger?.personId;
  const config = getWorkOrderCreateConfig();

  if (!isPersonAllowedToCreateWorkOrder(personId, config)) {
    await bot.say('You are not authorized to create work orders with this bot.');
    return;
  }

  const roomId = trigger?.message?.roomId;
  if (!roomId) {
    await bot.say('Could not determine the conversation to post the form.');
    return;
  }

  const card = buildCreateWorkOrderAdaptiveCard(config);
  const fallback =
    'Create ServiceChannel work order — open in Webex to fill out store, description, category, and priority.';

  const sender = typeof bot?.sendAdaptiveCard === 'function' ? bot : webexService;
  await sender.sendAdaptiveCard(roomId, card, fallback);
  logger('woCreate', `Posted create-WO card to room ${roomId} for person ${personId || 'unknown'}`);
}

export async function handleCreateWorkOrderSubmit(bot, trigger) {
  const action = trigger?.attachmentAction;
  if (!action?.inputs) return;

  const actionType = action.inputs.action;
  if (actionType === 'dismissCreateWoCard') {
    await _removeCardMessage(bot, action);
    try {
      await bot.say('Work order creation cancelled.');
    } catch (_) {}
    return;
  }

  if (actionType !== 'createWorkOrder') return;

  if (!isWorkOrderCreateEnabled()) {
    try {
      await bot.say('Work order creation is disabled on this bot.');
    } catch (_) {}
    return;
  }

  if (!isPersonAllowedToCreateWorkOrder(action.personId)) {
    try {
      await bot.say('You are not authorized to create work orders with this bot.');
    } catch (_) {}
    return;
  }

  const inputs = action.inputs;
  const storeId = String(inputs.storeId ?? '').trim();
  const description = String(inputs.description ?? '').trim();
  const category = String(inputs.category ?? '').trim();
  const priority = String(inputs.priority ?? '').trim();
  const problemCode = String(inputs.problemCode ?? '').trim();
  const nte = Number(inputs.nte);
  const config = getWorkOrderCreateConfig();

  if (!STORE_RE.test(storeId)) {
    try {
      await bot.say('Invalid store number — use 1–6 digits (e.g. **305** or **000305**).');
    } catch (_) {}
    return;
  }

  if (!description) {
    try {
      await bot.say('Description is required.');
    } catch (_) {}
    return;
  }

  if (!category || !priority) {
    try {
      await bot.say('Category and priority are required.');
    } catch (_) {}
    return;
  }

  if (config.requireIssueList && !problemCode) {
    try {
      await bot.say('Problem code is required for this tenant (`SC_CREATE_REQUIRE_ISSUELIST=true`).');
    } catch (_) {}
    return;
  }

  let submitter = 'Webex user';
  try {
    const botClientMod = await import('../integrations/webex/botClient.js');
    const details = await botClientMod.default.getPersonDetails(action.personId);
    submitter = details?.displayName || details?.emails?.[0] || submitter;
  } catch (err) {
    logger('woCreate:submit', `Could not resolve submitter: ${err.message}`, 'warn');
  }

  try {
    const contract = await resolveCreateContractInfo(storeId, {
      padLength: config.storePadLength,
      preferredTrade: config.tradeName,
    });

    const payload = buildCreateWorkOrderPayload({
      storeId: contract.storeId,
      locationId: contract.locationId,
      description: `${description}\n\n(Created via ServChan by ${submitter})`,
      category,
      priority,
      nte: Number.isFinite(nte) ? nte : config.defaultNte,
      tradeName: contract.tradeName,
      providerId: config.providerId,
      problemCode: problemCode || null,
      issueRequestInfo: config.issueRequestInfo,
    });

    const created = await createWorkOrder(payload);
    const woId = created?.Id ?? created?.id;
    const woNumber = created?.Number ?? created?.WorkorderNumber ?? woId;
    const scLink = woId
      ? `https://www.servicechannel.com/sc/wo/Workorders/index?id=${woId}`
      : 'https://www.servicechannel.com/sc/wo/Workorders';

    await _removeCardMessage(bot, action);

    await bot.say({
      markdown:
        `✅ **Work order created** · [WO-${woNumber}](${scLink})\n\n` +
        `- **Store:** ${contract.storeId}${contract.name ? ` (${contract.name})` : ''}\n` +
        `- **Trade / Provider:** ${contract.tradeName} · ${config.providerName}\n` +
        `- **Category / Priority:** ${category} · ${priority}\n\n` +
        `The ServChan group space will appear shortly when ServiceChannel sends the **WorkOrderCreated** webhook.`,
    });

    logger(
      'woCreate:submit',
      `Created WO ${woId || woNumber} for store ${contract.storeId} (${contract.tradeName}, ${config.providerName}) by ${submitter}`
    );
  } catch (err) {
    const msg = err.message || String(err);
    const isTokenError = msg.includes('token fetch failed');
    const reply = isTokenError
      ? `❌ **ServiceChannel login failed** — check SC credentials and restart ServChan.`
      : `❌ **Failed to create work order:** ${msg}\n\nVerify store, category, priority, and trade/provider settings. Use \`GET /create-wo-discovery\` (admin) to inspect tenant defaults.`;

    try {
      await bot.say({ markdown: reply });
    } catch (_) {}

    logger('woCreate:submit', `Create failed for store ${storeId}: ${msg}`, 'error');
  }
}

export default {
  buildCreateWorkOrderAdaptiveCard,
  postCreateWorkOrderCard,
  handleCreateWorkOrderSubmit,
};
