import { getIsDevMode, getTelegramBotToken, getTelegramChatIds } from '@/src/lib/env-exporter' export interface TelegramCred { botToken: string chatId: string } const postToChat = async (botToken: string, chatId: string, message: string): Promise => { try { const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'HTML' }), }) const data = await response.json() as { ok: boolean } if (data.ok) { console.log(`Telegram message sent successfully to ${chatId}`) return true } else { console.error(`Telegram API error for ${chatId}:`, data) return false } } catch (error) { console.error(`Failed to send Telegram message to ${chatId}:`, error) return false } } export const sendTelegramMessage = async (message: string): Promise => { if (getIsDevMode()) { return null; } const botToken = getTelegramBotToken() const chatIds = getTelegramChatIds() if (!botToken || chatIds.length === 0) { console.warn('Telegram credentials not configured, skipping notification') return null } try { const results = await Promise.all( chatIds.map(async (chatId) => postToChat(botToken, chatId, message)) ) console.log('sent telegram message successfully') return results.some((result) => result) } catch (error) { console.error('Failed to send Telegram message:', error) return false } } /** Region-scoped fan-out: one message to every cred of the order's region. */ export const sendTelegramMessageToCreds = async ( message: string, creds: TelegramCred[] ): Promise => { if (getIsDevMode()) { return null; } if (creds.length === 0) { console.warn('No Telegram creds provided, skipping notification') return null } try { const results = await Promise.all( creds.map(async (cred) => postToChat(cred.botToken, cred.chatId, message)) ) console.log('sent telegram message successfully') return results.some((result) => result) } catch (error) { console.error('Failed to send Telegram message:', error) return false } }