import { registerChannel } from "./registry.js";
const API = (token) => `https://api.telegram.org/bot${token}`;
export class TelegramChannel {
    name = "telegram";
    opts;
    offset = 0;
    running = false;
    handler;
    constructor(opts) {
        if (!opts.token)
            throw new Error("telegram: token is required");
        this.opts = opts;
    }
    async start(handler) {
        this.handler = handler;
        this.running = true;
        // Disable any old webhook so long-poll works.
        try {
            await this.api("deleteWebhook", { drop_pending_updates: false });
        }
        catch { }
        void this.poll();
    }
    async stop() {
        this.running = false;
    }
    async send(msg) {
        const chatId = msg.threadId ?? msg.to;
        await this.api("sendMessage", {
            chat_id: parseInt(chatId, 10) || chatId,
            text: msg.text,
            parse_mode: "Markdown",
        });
    }
    async poll() {
        while (this.running) {
            try {
                const updates = await this.api("getUpdates", {
                    offset: this.offset,
                    timeout: this.opts.longPollSec ?? 30,
                    allowed_updates: ["message"],
                });
                for (const u of updates) {
                    if (u.update_id >= this.offset)
                        this.offset = u.update_id + 1;
                    const m = u.message;
                    if (!m || !m.text)
                        continue;
                    if (!this.allowed(m))
                        continue;
                    await this.handler?.({
                        channel: this.name,
                        from: String(m.chat.id),
                        text: m.text,
                        threadId: String(m.chat.id),
                        receivedAt: new Date(m.date * 1000),
                    });
                }
            }
            catch (err) {
                console.error(`[telegram] poll error: ${err.message}`);
                await new Promise((r) => setTimeout(r, 3_000));
            }
        }
    }
    allowed(m) {
        if (this.opts.allowedChatIds?.length) {
            if (!this.opts.allowedChatIds.includes(m.chat.id))
                return false;
        }
        if (this.opts.allowedUsernames?.length) {
            const u = (m.from?.username ?? "").toLowerCase();
            if (!u || !this.opts.allowedUsernames.map((x) => x.toLowerCase()).includes(u)) {
                return false;
            }
        }
        return true;
    }
    async api(method, body) {
        const res = await fetch(`${API(this.opts.token)}/${method}`, {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(body),
        });
        const json = (await res.json());
        if (!json.ok)
            throw new Error(`telegram ${method}: ${json.description}`);
        return json.result;
    }
}
registerChannel("telegram", (cfg) => {
    return new TelegramChannel({
        token: String(cfg.token ?? ""),
        allowedChatIds: Array.isArray(cfg.allowedChatIds)
            ? cfg.allowedChatIds
            : undefined,
        allowedUsernames: Array.isArray(cfg.allowedUsernames)
            ? cfg.allowedUsernames
            : undefined,
        longPollSec: typeof cfg.longPollSec === "number" ? cfg.longPollSec : undefined,
    });
});
//# sourceMappingURL=telegram.js.map