import { assertTelegramBotConfiguration, telegramBotConfig } from "./config.js";
import { getTelegramBot } from "./bot.js";

let started = false;

export const startTelegramBot = async () => {
  if (!telegramBotConfig.enabled || started) {
    return;
  }

  assertTelegramBotConfiguration();
  const bot = getTelegramBot();

  if (telegramBotConfig.mode === "polling") {
    started = true;
    void bot
      .launch(
        {
          dropPendingUpdates: false,
          allowedUpdates: ["message", "callback_query"],
        },
        () => {
          console.log("✅ TELEGRAM BOT IS RUNNING IN POLLING MODE", {
            info: bot.botInfo,
            config: telegramBotConfig,
          });
        },
      )
      .catch((error) => {
        started = false;
        console.error(
          "❌ TELEGRAM BOT POLLING FAILED",
          error?.message || "unknown error",
        );
      });
    return;
  }

  await bot.telegram.setWebhook(telegramBotConfig.webhookUrl, {
    secret_token: telegramBotConfig.webhookSecret,
    allowed_updates: ["message", "callback_query"],
  });
  started = true;
  console.log(
    "✅ TELEGRAM BOT WEBHOOK IS CONFIGURED:",
    telegramBotConfig.webhookUrl,
  );
};

export const stopTelegramBot = async (reason = "shutdown") => {
  if (!started || !telegramBotConfig.enabled) {
    return;
  }

  getTelegramBot().stop(reason);
  started = false;
};

export { getTelegramBot, telegramBotConfig };
