import express from 'express';
import { sendToJDownloader } from '../utils/jdownloader.js';
import authMiddleware from '../utils/authMiddleware.js';
import apiLimiter from '../utils/rateLimiter.js';

const router = express.Router();

router.post('/api/jd/add', apiLimiter, authMiddleware, async (req, res) => {
    const { link, links, packageName, isSeries } = req.body;
    
    let list: string[] = [];
    if (Array.isArray(links)) {
        list = links.map(l => l.trim()).filter(Boolean);
    } else if (typeof links === 'string') {
        list = links.split('\n').map(l => l.trim()).filter(Boolean);
    }
    if (link && typeof link === 'string') {
        const trimmed = link.trim();
        if (trimmed && !list.includes(trimmed)) {
            list.push(trimmed);
        }
    }

    if (list.length === 0) {
        return res.status(400).json({ error: "Aucun lien valide fourni." });
    }

    try {
        for (const url of list) {
            await sendToJDownloader(url, packageName || 'Manual Add', !!isSeries);
        }
        res.json({ success: true, count: list.length });
    } catch (error: any) {
        res.status(500).json({ error: error.message });
    }
});

export default router;
