import type { TelegramChannelConfig } from '../types.js';
import type { SendResult } from './email.js';

export interface TelegramMessage {
  text: string;
  chatId: string;
  disableNotification?: boolean;
}

export async function sendTelegramMessage(
  message: TelegramMessage,
  config: TelegramChannelConfig
): Promise<SendResult> {
  if (!config.botToken) {
    return { success: false, error: 'Telegram bot token not configured' };
  }

  try {
    const response = await fetch(`https://api.telegram.org/bot${config.botToken}/sendMessage`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        chat_id: message.chatId,
        text: message.text,
        disable_notification: message.disableNotification ?? false,
      }),
    });

    const payload = (await response.json()) as {
      ok?: boolean;
      description?: string;
      result?: { message_id?: number };
    };

    if (!response.ok || !payload.ok) {
      return {
        success: false,
        error: payload.description || `Telegram error ${response.status}`,
      };
    }

    return {
      success: true,
      messageId:
        typeof payload.result?.message_id === 'number'
          ? String(payload.result.message_id)
          : `telegram_${crypto.randomUUID()}`,
    };
  } catch (err: unknown) {
    return { success: false, error: err instanceof Error ? err.message : String(err) };
  }
}
