/**
 * Cliente mínimo da Telegram Bot API (HTTP). Só o necessário para a ponte:
 * enviar mensagem ao grupo e ler updates (replies dos operadores).
 *
 * O token vem de `app_settings` (criptografado) — nunca do código/env.
 */

export interface TelegramMessage {
  message_id: number;
  text?: string;
  chat: { id: number };
  reply_to_message?: { message_id: number };
  from?: { id: number; first_name?: string; username?: string };
}

export interface TelegramUpdate {
  update_id: number;
  message?: TelegramMessage;
}

export class TelegramBot {
  constructor(private readonly token: string) {}

  private url(method: string): string {
    return `https://api.telegram.org/bot${this.token}/${method}`;
  }

  private async call<T>(method: string, body?: unknown): Promise<T> {
    const res = await fetch(this.url(method), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: body ? JSON.stringify(body) : undefined,
    });
    const data = (await res.json()) as { ok: boolean; result?: T; description?: string };
    if (!data.ok) {
      throw new Error(`Telegram ${method} falhou: ${data.description ?? res.status}`);
    }
    return data.result as T;
  }

  /** Envia mensagem (HTML) e devolve o message_id postado. */
  async sendMessage(
    chatId: string | number,
    text: string,
    opts?: { replyMarkup?: unknown },
  ): Promise<number> {
    const msg = await this.call<TelegramMessage>("sendMessage", {
      chat_id: chatId,
      text,
      parse_mode: "HTML",
      disable_web_page_preview: true,
      reply_markup: opts?.replyMarkup,
    });
    return msg.message_id;
  }

  /** Long-poll de updates a partir de um offset. */
  async getUpdates(offset: number, timeoutSec = 0): Promise<TelegramUpdate[]> {
    return this.call<TelegramUpdate[]>("getUpdates", {
      offset,
      timeout: timeoutSec,
      allowed_updates: ["message"],
    });
  }
}
