import { detectMime } from "../media/mime.js";
import { saveMediaBuffer } from "../media/store.js";
export class TelegramDownloadError extends Error {
    code;
    constructor(code, message) {
        super(message);
        this.code = code;
        this.name = "TelegramDownloadError";
    }
}
export async function getTelegramFile(token, fileId, options) {
    const fetcher = options?.fetchImpl ?? globalThis.fetch;
    if (!fetcher) {
        throw new TelegramDownloadError("fetch_failed", "fetch is not available; set channels.telegram.proxy in config");
    }
    let res;
    try {
        res = await fetcher(`https://api.telegram.org/bot${token}/getFile?file_id=${encodeURIComponent(fileId)}`);
    }
    catch (err) {
        throw new TelegramDownloadError("fetch_failed", `Failed to fetch Telegram file info: ${err instanceof Error ? err.message : String(err)}`);
    }
    if (!res.ok) {
        throw new TelegramDownloadError("http_error", `getFile failed: ${res.status} ${res.statusText}`);
    }
    const json = (await res.json());
    if (!json.ok || !json.result?.file_path) {
        throw new TelegramDownloadError("api_error", json.description ?? "getFile returned no file_path");
    }
    return json.result;
}
export async function downloadTelegramFile(token, info, maxBytes, options) {
    if (!info.file_path) {
        throw new TelegramDownloadError("api_error", "file_path missing");
    }
    const fetcher = options?.fetchImpl ?? globalThis.fetch;
    if (!fetcher) {
        throw new TelegramDownloadError("fetch_failed", "fetch is not available; set channels.telegram.proxy in config");
    }
    const url = `https://api.telegram.org/file/bot${token}/${info.file_path}`;
    let res;
    try {
        res = await fetcher(url);
    }
    catch (err) {
        throw new TelegramDownloadError("fetch_failed", `Failed to download Telegram file: ${err instanceof Error ? err.message : String(err)}`);
    }
    if (!res.ok || !res.body) {
        throw new TelegramDownloadError("http_error", `Failed to download telegram file: HTTP ${res.status}`);
    }
    const array = Buffer.from(await res.arrayBuffer());
    const mime = await detectMime({
        buffer: array,
        headerMime: res.headers.get("content-type"),
        filePath: info.file_path,
    });
    // save with inbound subdir
    const saved = await saveMediaBuffer(array, mime, "inbound", maxBytes);
    // Ensure extension matches mime if possible
    if (!saved.contentType && mime)
        saved.contentType = mime;
    return saved;
}
