import env from "$env/index.js";

const parseBoolean = (value, fallback = false) => {
  if (value === undefined || value === null || value === "") {
    return fallback;
  }

  return String(value).trim().toLowerCase() === "true";
};

const normalizeBaseUrl = (value = "") =>
  String(value).trim().replace(/\/+$/, "");

const parseNationalCodes = (value = "") =>
  String(value)
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);

const enabled = parseBoolean(env.TELEGRAM_BOT_ENABLED, false);
const mode = String(env.TELEGRAM_BOT_MODE || "webhook")
  .trim()
  .toLowerCase();
const developmentMode = parseBoolean(env.TELEGRAM_BOT_DEVELOPMENT_MODE, true);
const publicBaseUrl = normalizeBaseUrl(
  env.TELEGRAM_BOT_PUBLIC_BASE_URL || env.API_PUBLIC_BASE_URL,
);

/**
 * Telegram bot runtime configuration.
 *
 * enabled:
 *   Master switch. When false, the bot runtime does not start and /v1/bot
 *   routes are not mounted.
 * token:
 *   Bot API token issued by BotFather. Required whenever the bot is enabled.
 * mode:
 *   "polling" for local/development use or "webhook" for deployed instances.
 * webhookSecret:
 *   Secret expected in Telegram's X-Telegram-Bot-Api-Secret-Token header.
 *   Required in webhook mode.
 * webhookPath / webhookUrl:
 *   Isolated API callback path and its fully-qualified public HTTPS URL.
 * developmentMode / allowedNationalCodes:
 *   When enabled, authentication is limited to TELEGRAM_BOT_TEST_NATIONAL_CODES.
 * stateTtlSeconds:
 *   Lifetime of an unfinished Redis-backed conversation.
 * quoteTtlSeconds:
 *   Lifetime of a server-calculated investment confirmation quote.
 */
export const telegramBotConfig = Object.freeze({
  enabled,
  token: String(env.TELEGRAM_BOT_TOKEN || "").trim(),
  mode: mode === "polling" ? "polling" : "webhook",
  webhookSecret: String(env.TELEGRAM_BOT_WEBHOOK_SECRET || "").trim(),
  webhookPath: "/v1/bot/webhook",
  webhookUrl: publicBaseUrl ? `${publicBaseUrl}/v1/bot/webhook` : "",
  developmentMode,
  allowedNationalCodes: parseNationalCodes(
    env.TELEGRAM_BOT_TEST_NATIONAL_CODES,
  ),
  stateTtlSeconds: Math.max(
    300,
    Number(env.TELEGRAM_BOT_STATE_TTL_SECONDS || 15 * 60),
  ),
  quoteTtlSeconds: Math.max(
    60,
    Number(env.TELEGRAM_BOT_QUOTE_TTL_SECONDS || 5 * 60),
  ),
});

export const assertTelegramBotConfiguration = () => {
  if (!telegramBotConfig.enabled) {
    return;
  }

  if (!telegramBotConfig.token) {
    throw new Error(
      "TELEGRAM_BOT_TOKEN is required when TELEGRAM_BOT_ENABLED=true.",
    );
  }

  if (
    telegramBotConfig.mode === "webhook" &&
    (!telegramBotConfig.webhookUrl || !telegramBotConfig.webhookSecret)
  ) {
    throw new Error(
      "TELEGRAM_BOT_PUBLIC_BASE_URL and TELEGRAM_BOT_WEBHOOK_SECRET are required in webhook mode.",
    );
  }

  if (
    telegramBotConfig.developmentMode &&
    telegramBotConfig.allowedNationalCodes.length === 0
  ) {
    throw new Error(
      "TELEGRAM_BOT_TEST_NATIONAL_CODES must contain at least one identifier when TELEGRAM_BOT_DEVELOPMENT_MODE=true.",
    );
  }
};
