import type { MinionPluginApi } from "../../../src/plugins/types.js";
import type { ComplaintResult } from "./types.js";

const SEVERITY_EMOJI: Record<string, string> = {
  low: "🟡",
  med: "🟠",
  high: "🔴",
};

const CATEGORY_LABEL: Record<string, string> = {
  product_defect: "Product defect",
  billing: "Billing",
  delivery: "Delivery",
  service: "Service",
  other: "Other",
};

export type DeliveryTargets = {
  telegramChatId: string;
  whatsappTo: string;
};

export type DeliveryResult = {
  telegram: boolean;
  whatsapp: boolean;
};

export function formatNotification(
  agentId: string,
  channelId: string,
  fromSender: string,
  result: ComplaintResult,
): string {
  const emoji = SEVERITY_EMOJI[result.severity] ?? "⚪";
  const category = CATEGORY_LABEL[result.category] ?? result.category;
  const lines = [
    `${emoji} *Complaint detected* (${result.severity.toUpperCase()})`,
    `Agent: ${agentId} | Channel: ${channelId}`,
    `From: ${fromSender}`,
    `Category: ${category}`,
  ];
  if (result.summary) {
    lines.push(`Summary: ${result.summary}`);
  }
  return lines.join("\n");
}

async function sendWhatsApp(api: MinionPluginApi, to: string, text: string): Promise<boolean> {
  if (!to) {
    api.logger.warn(
      "complaint-listener: COMPLAINTS_NOTIFY_WHATSAPP_TO not set; skipping WA notify",
    );
    return false;
  }
  try {
    await api.runtime.channel.whatsapp.sendMessageWhatsApp(to, text, { verbose: false });
    return true;
  } catch (err) {
    api.logger.error(`complaint-listener: WhatsApp notify failed: ${String(err)}`);
    return false;
  }
}

async function sendTelegram(api: MinionPluginApi, chatId: string, text: string): Promise<boolean> {
  if (!chatId) {
    api.logger.warn(
      "complaint-listener: COMPLAINTS_NOTIFY_TELEGRAM_CHAT_ID not set; skipping TG notify",
    );
    return false;
  }
  try {
    await api.runtime.channel.telegram.sendMessageTelegram(chatId, text, { textMode: "markdown" });
    return true;
  } catch (err) {
    api.logger.error(`complaint-listener: Telegram notify failed: ${String(err)}`);
    return false;
  }
}

export async function sendComplaintNotification(
  api: MinionPluginApi,
  targets: DeliveryTargets,
  agentId: string,
  channelId: string,
  fromSender: string,
  result: ComplaintResult,
): Promise<DeliveryResult> {
  const message = formatNotification(agentId, channelId, fromSender, result);
  const [tg, wa] = await Promise.all([
    sendTelegram(api, targets.telegramChatId, message),
    sendWhatsApp(api, targets.whatsappTo, message),
  ]);
  return { telegram: tg, whatsapp: wa };
}
