/**
 * Lightweight Telegram client for the mirror's manager channel.
 *
 * Distinct from the gateway's grammy-based bot: this is outbound-only
 * (sendMessage via fetch) and uses its own bot token + chat id specified in
 * MIRROR_TELEGRAM_BOT_TOKEN / MIRROR_TELEGRAM_CHAT_ID. The code is structured
 * so that incoming-update handling (long polling / webhooks) can be added
 * later without rewriting callers.
 */
import { config } from '../config';

type SendExtra = {
  disable_notification?: boolean;
  reply_markup?: unknown;
};

function maskToken(token: string | undefined): string {
  if (!token) return '<empty>';
  if (token.length <= 12) return `${token.slice(0, 4)}…`;
  return `${token.slice(0, 6)}…${token.slice(-4)}`;
}

function esc(text?: unknown): string {
  if (text === undefined || text === null) return '';
  return String(text)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function fmtAmount(amount: number, currency: string): string {
  return `${amount.toFixed(2)} ${currency}`;
}

let warnedDisabled = false;

async function sendRaw(text: string, extra: SendExtra = {}): Promise<void> {
  const token = config.mirrorTg.token;
  const chatId = config.mirrorTg.chatId;
  if (!token || !chatId) {
    if (!warnedDisabled) {
      warnedDisabled = true;
      console.log('[mirror-tg] disabled (missing MIRROR_TELEGRAM_BOT_TOKEN/CHAT_ID)');
    }
    return;
  }
  try {
    const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: chatId,
        text,
        parse_mode: 'HTML',
        disable_web_page_preview: true,
        ...extra,
      }),
    });
    if (!res.ok) {
      const body = await res.text().catch(() => '');
      console.error(
        `[mirror-tg] sendMessage failed status=${res.status} token=${maskToken(token)} body=${body.slice(0, 200)}`,
      );
    }
  } catch (err) {
    console.error('[mirror-tg] sendMessage error:', (err as Error).message);
  }
}

/** Best-effort fire-and-forget; never throws into caller. */
export function notify(text: string, extra: SendExtra = {}): void {
  void sendRaw(text, extra);
}

