import type { JobsOptions } from "bullmq";
import { prisma } from "../utils/prisma";
import { telegramApiBase, requireTelegramBotToken } from "../utils/telegram";
import { enqueueOutboundDelivery, startOutboundDeliveryWorker } from "./outboundDelivery";

type TelegramSendJob = {
  omniMessageId: string;
};

export async function enqueueTelegramSend(input: TelegramSendJob, opts?: JobsOptions) {
  const msg = await prisma.omniMessage.findUnique({
    where: { id: input.omniMessageId },
    include: { thread: true },
  });
  if (!msg) throw new Error(`omni message not found: ${input.omniMessageId}`);
  if (msg.channel !== "TELEGRAM" || msg.direction !== "OUT") {
    throw new Error(`Invalid omni message for telegram send: ${msg.id}`);
  }

  const token = requireTelegramBotToken();
  const endpoint = `${telegramApiBase()}/bot${token}/sendMessage`;
  const payload = {
    chat_id: msg.thread.externalChatId,
    text: msg.text,
    ...(msg.thread.businessConnectionId ? { business_connection_id: msg.thread.businessConnectionId } : {}),
  };

  return enqueueOutboundDelivery(
    {
      omniMessageId: msg.id,
      endpoint,
      method: "POST",
      payload,
      provider: "telegram_business",
      channel: "TELEGRAM",
    },
    opts,
  );
}

export function startTelegramSendWorker() {
  return startOutboundDeliveryWorker();
}
