import express from 'express';
import { Database } from '../database/database.js';
import {
  facebookdl,
  savefrom,
  snapsave,
  tiktokdl,
  sfilemobi,
  capcutdl,
  PinterestDL,
  sfilemobiSearch,
  TiktokDownloader,
  TwitterDownloader,
  TwitterDownloderV3,
  TwitterDownloaderV2,
  TeraboxDownloader,
  TeraboxV2Downloader,
  TeraboxV3Downloader,
  TeraboxV4Downloader,
  XnxxDownloader,
  XsearchDownloaderV2,
  InstagramDownloader,
  InstagramDLV3,
  InstagramDLV2,
  InstagramDLV4,
  XInfoDownloaderV2,
  TelegramUseLog,
} from '../lib/all.js';

import { authenticateApiKey, apiLimiter } from '../middleware/midware.js';
const AllDlRoutes = express.Router();

const dbClient = new Database("AkenoXJs");
const db = dbClient.collection("api_keys");

async function updateIP(apiKey, newIP) {
    await db.updateOne(
        { key: apiKey },
        { $addToSet: { ip_addresses: newIP } }
    );
}


async function downloadMedia(media) {
    const downloadResults = {};
    try {
        if (media.audio && Object.keys(media.audio).length > 0) {
            const audioQuality = Object.keys(media.audio)[0];
            const audioDownloadUrl = await media.audio[audioQuality].download();
            downloadResults.audio = {
                quality: audioQuality,
                url: audioDownloadUrl
            };
        }

        return downloadResults;
    } catch (error) {
        console.error("Error downloading media:", error);
        throw new Error("Failed to download media");
    }
}

/**
 * @swagger
 * /api/v1/dl/terabox-v4:
 *   get:
 *     summary: Terabox V4 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/terabox-v4', async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TeraboxV4Downloader(q);
        res.json({ message: results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/twitter-v3:
 *   get:
 *     summary: Twitter V3 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/twitter-v3', async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TwitterDownloderV3(q);
        res.json({ message: results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/twitter-v2:
 *   get:
 *     summary: Twitter V2 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/twitter-v2', async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TwitterDownloaderV2(q);
        res.json({ message: results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/xnxx-info-v2:
 *   get:
 *     summary: Xnxx Info V2 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/xnxx-info-v2', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;

        if (!q) {
            return res.status(400).json({ error: "url parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await XInfoDownloaderV2(q);
        res.json({ message: results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/xnxx-search-v2:
 *   get:
 *     summary: Xnxx Search V2 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: q
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/xnxx-search-v2', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.q;
        if (!q) {
            return res.status(400).json({ error: "q parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await XsearchDownloaderV2(q);
        res.json({ message: results });
        // console.dir(testings);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/instagram-v4:
 *   get:
 *     summary: Instagram V4 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/instagram-v4', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;

        if (!q) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await InstagramDLV4(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


/**
 * @swagger
 * /api/v1/dl/instagram-v3:
 *   get:
 *     summary: Instagram V3 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/instagram-v3', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;
        if (!q) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await InstagramDLV3(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/instagram-v2:
 *   get:
 *     summary: Instagram V2 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/instagram-v2', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.url;

        if (!q) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await InstagramDLV2(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/pint:
 *   get:
 *     summary: Pinterest Search Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: q
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/pint', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.q;

        if (!q) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await PinterestDL(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


/**
 * @swagger
 * /api/v1/dl/sfilemobi-search:
 *   get:
 *     summary: Sfilemobi Search Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: q
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/sfilemobi-search', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.q;

        if (!q) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await sfilemobiSearch(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


/* AllDlRoutes.get('/api/v1/dl/terabox-v3', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        const results = await TeraboxV3Downloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});
 */


/* AllDlRoutes.get('/api/v1/dl/terabox-v2', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TeraboxV2Downloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
}); */


/* AllDlRoutes.get('/api/v1/dl/terabox', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TeraboxDownloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});
 */

/**
 * @swagger
 * /api/v1/dl/capcut:
 *   get:
 *     summary: Capcut Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/capcut', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = capcutdl(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


/**
 * @swagger
 * /api/v1/dl/instagram:
 *   get:
 *     summary: Instagram Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/instagram', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await InstagramDownloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/twitter:
 *   get:
 *     summary: Twitter Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/twitter', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TwitterDownloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/sfilemobi:
 *   get:
 *     summary: Sfilemobi Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/sfilemobi', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await sfilemobi(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/tiktok:
 *   get:
 *     summary: Tiktok Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: The URL of the TikTok video to be processed
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/tiktok', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await TiktokDownloader(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/tiktok-v2:
 *   get:
 *     summary: Tiktok V2 Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: The URL of the TikTok video to be processed
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid URL)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/tiktok-v2', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }

        const url = req.query.url;
        if (!url) {
            return res.status(400).json({ error: "URL parameter is required." });
        }

        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );

        const results = await tiktokdl(url);
        res.json({ results });

    } catch (error) {
        console.error("TikTok Downloader Error:", error.message);
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/fb:
 *   get:
 *     summary: FB Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid url)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/fb', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }

        const url = req.query.url;
        if (!url) {
            return res.status(400).json({ error: "url parameter is required." });
        }

        const results = await facebookdl(url);

        for (const video of results.video) {
            video.url = await video.download();
        }
        for (const audio of results.audio) {
            audio.url = await audio.download();
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/snapsave:
 *   get:
 *     summary: SnapSave Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid url)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/snapsave', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
  
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "url parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await snapsave(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/savefrom:
 *   get:
 *     summary: Savefrom Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         description: null
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid url)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/savefrom', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const url = req.query.url;

        if (!url) {
            return res.status(400).json({ error: "url parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await savefrom(url);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @swagger
 * /api/v1/dl/xnxx:
 *   get:
 *     summary: Xnxx Downloader
 *     tags: [ALL-Downloader]
 *     parameters:
 *       - in: query
 *         name: q
 *         required: true
 *         description: The search of the Xnxx video to be processed
 *         schema:
 *           type: string
 *       - in: header
 *         name: x-api-key
 *         required: true
 *         description: API key for authentication
 *         schema:
 *           type: string
 *           example: "lu api key di @aknuserbot telegram"
 *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description: Bad Request (e.g., missing or invalid q)
 *       401:
 *         description: Unauthorized (e.g., missing or invalid API key)
 *       500:
 *         description: Internal Server Error
 */
AllDlRoutes.get('/api/v1/dl/xnxx', authenticateApiKey, apiLimiter, async (req, res) => {
    try {
        const apiKey = req.headers['x-api-key'];
        const userAgent = req.headers['user-agent'];

        const xForwardedFor = req.headers['x-forwarded-for'];
        const xRealIP = req.headers['x-real-ip'];
        const cfConnectingIP = req.headers['cf-connecting-ip'];

        let realIP = req.ip;

        if (xForwardedFor) {
            realIP = xForwardedFor.split(',')[0].trim();
        } else if (xRealIP) {
            realIP = xRealIP;
        } else if (cfConnectingIP) {
            realIP = cfConnectingIP;
        }

        req.realIP = realIP;

        console.log(`🔍 Captured IPs:`, { xForwardedFor, xRealIP, cfConnectingIP, realIP });

        const keyDoc = await db.findOne({ key: apiKey });

        if (!keyDoc) {
            return res.status(403).json({ error: "Invalid API Key." });
        }
        const q = req.query.q;

        if (!q) {
            return res.status(400).json({ error: "q parameter is required." });
        }
        await updateIP(apiKey, realIP);
        await TelegramUseLog(
            keyDoc.owner,
            keyDoc.key,
            `Accessed: ${req.path}\nRealIP: ${realIP}\nUser-Agent: ${userAgent}`
        );
        const results = await XnxxDownloader(q);
        res.json({ results });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

export { AllDlRoutes };