const axios = require("axios");

module.exports.config = {
    name: "Downlink",
    version: "2.1.0",
    hasPermssion: 0,
    credits: "gấu lỏ",
    description: "Tải video/ảnh từ các nền tảng",
    commandCategory: "Tiện ích",
    usages: "Tự động hoạt động khi có link",
    cooldowns: 5
};

module.exports.run = async function () { };

module.exports.handleEvent = async function ({ api, event }) {
    const { threadID, messageID, body } = event;
    if (!body) return;

    const urls = body.match(/https?:\/\/[\w\d\-._~:/?#[\]@!$&'()*+,;=%]+/g);
    if (!urls) return;
    const url = urls[0];

    const supported = [
        "facebook.com", "tiktok.com", "douyin.com",
        "instagram.com", "threads.net", "youtube.com",
        "youtu.be", "capcut.com", "threads.com"
    ];
    if (!supported.some(domain => url.includes(domain))) return;

    try {
        const response = await axios.post(
            "https://downr.org/.netlify/functions/download",
            { url },
            {
                headers: {
                    "accept": "*/*",
                    "content-type": "application/json",
                    "origin": "https://downr.org",
                    "referer": "https://downr.org/",
                    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
                }
            }
        );

        const data = response.data;
        if (!data || !Array.isArray(data.medias)) return;

        const title = data.title || "Không có tiêu đề";
        const author = data.author || "Không rõ";
        const header = `[${(data.source || "Unknown").toUpperCase()}] - Tự Động Tải\n\n👤 Tác giả: ${author}\n💬 Tiêu đề: ${title}`;
        const videoList = data.medias.filter(m => m.type === "video");
        let bestVideo = null;
        if (videoList.length > 0) {
            bestVideo =
                videoList.find(v => v.quality === "hd_no_watermark") ||
                videoList.find(v => v.quality === "no_watermark") ||
                videoList[0];
        }
        const images = data.medias.filter(m => m.type === "image").map(img => img.url);
        const attachments = [];
        for (const imgUrl of images) {
            const imgStream = (await axios.get(imgUrl, { responseType: "stream" })).data;
            attachments.push(imgStream);
        }
        if (bestVideo) {
            const videoStream = (await axios.get(bestVideo.url, { responseType: "stream" })).data;
            attachments.push(videoStream);
        }

        if (attachments.length) {
            await api.sendMessage({
                body: header,
                attachment: attachments
            }, threadID, messageID);
        }

    } catch (err) {
        console.error("❌ Lỗi tải media:", err.message || err);
    }
};