import { randomBytes } from "node:crypto";
import { writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
const TELEGRAM_API = "https://api.telegram.org";
export async function sendMessage(botToken, options) {
    const res = await fetch(`${TELEGRAM_API}/bot${botToken}/sendMessage`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            chat_id: options.chatId,
            text: options.text,
            parse_mode: options.parseMode ?? "HTML",
            reply_markup: options.replyMarkup
                ? JSON.stringify(options.replyMarkup)
                : undefined,
        }),
    });
    const data = (await res.json());
    if (!data.ok) {
        return { ok: false, error: data.description ?? "Unknown Telegram error" };
    }
    return { ok: true, messageId: data.result?.message_id };
}
/**
 * Register a webhook URL with Telegram and generate a cryptographic secret.
 *
 * The secret is:
 *   1. Generated via crypto.randomBytes (64 hex chars)
 *   2. Passed to the Telegram Bot API as secret_token
 *   3. Written to secretFilePath on disk ONLY after the API confirms success
 *
 * Telegram sends this secret in the X-Telegram-Bot-Api-Secret-Token header
 * on every webhook delivery. The webhook route validates it before processing.
 *
 * If secretFilePath is omitted, no secret is generated (backward compat for tests).
 */
export async function setWebhook(botToken, webhookUrl, secretFilePath) {
    const secret = secretFilePath ? randomBytes(32).toString("hex") : undefined;
    const body = { url: webhookUrl };
    if (secret) {
        body.secret_token = secret;
    }
    const res = await fetch(`${TELEGRAM_API}/bot${botToken}/setWebhook`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
    });
    const data = (await res.json());
    if (!data.ok) {
        return { ok: false, error: data.description ?? "Failed to set webhook" };
    }
    // Write secret to disk only after Telegram confirms the webhook registration.
    // This prevents orphaned secret files when the API call fails, and avoids
    // overwriting a working secret during a failed re-registration attempt.
    if (secret && secretFilePath) {
        mkdirSync(dirname(secretFilePath), { recursive: true });
        writeFileSync(secretFilePath, secret, { mode: 0o600 });
        console.error(`[telegram] webhook secret written to ${secretFilePath} (${secret.length} chars)`);
    }
    return { ok: true, secret };
}
export async function getWebhookInfo(botToken) {
    const res = await fetch(`${TELEGRAM_API}/bot${botToken}/getWebhookInfo`);
    const data = (await res.json());
    return {
        url: data.result.url,
        pendingUpdateCount: data.result.pending_update_count,
    };
}
//# sourceMappingURL=telegram.js.map