const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
const buildTelegramUrl = (token: string) => `https://api.telegram.org/bot${token}/sendMessage`;

export async function sendTelegramMessage(text: string) {
  if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
    console.error('Telegram credentials missing in environment');
    throw new Error('telegram configuration missing');
  }

  const response = await fetch(buildTelegramUrl(TELEGRAM_BOT_TOKEN), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: TELEGRAM_CHAT_ID,
      text,
    }),
  });

  if (!response.ok) {
    const details = await response.text();
    console.error('Telegram request failed', details);
    throw new Error(details);
  }
}
