import type { TelegramTransport, TelegramUpdate } from "./adapter.ts";

export async function createGrammyTransport(token: string): Promise<TelegramTransport | null> {
  if (!token.trim()) return null;
  let grammy: any;
  try {
    grammy = await import("grammy");
  } catch {
    return null;
  }
  const bot = new grammy.Bot(token);
  return {
    async getMe() {
      return bot.api.getMe();
    },
    async start(handler: (update: TelegramUpdate) => Promise<void>) {
      bot.on("message", async (ctx: any) => handler({ update_id: ctx.update?.update_id, message: ctx.message }));
      bot.on("edited_message", async (ctx: any) => handler({ update_id: ctx.update?.update_id, edited_message: ctx.editedMessage }));
      await bot.start({ allowed_updates: ["message", "edited_message"] });
    },
    async stop() {
      await bot.stop();
    },
    async sendMessage(chatId, text, options) {
      return bot.api.sendMessage(chatId, text, options ?? {});
    },
    async editMessageText(chatId, messageId, text, options) {
      return bot.api.editMessageText(chatId, Number(messageId), text, options ?? {});
    },
    async setMessageReaction(chatId, messageId, emoji) {
      const reaction = emoji ? [{ type: "emoji", emoji }] : [];
      return bot.api.setMessageReaction(chatId, Number(messageId), reaction);
    },
  };
}
