const express = require('express');
const path = require('path');
const fs = require('fs');
const archiver = require('archiver');
const router = express.Router();

// Route for downloading files as a zip
router.get('/download-zip', (req, res) => {
    console.log('Received download zip request');

    // Get the file paths from the query parameters
    const filePaths = req.query.paths ? JSON.parse(req.query.paths) : [];

    if (!filePaths || filePaths.length === 0) {
        console.error('No file paths provided');
        return res.status(400).send('No files selected for download.');
    }

    console.log('Selected file paths:', filePaths);

    // Directory where files are stored (private folder)
    const privateFolderPath = path.join(__dirname, '../private');

    // If only one file is selected, download it directly
    if (filePaths.length === 1) {
        const filePath = filePaths[0];

        // Decode and normalize the file path
        const decodedFilePath = decodeURIComponent(filePath).replace(/%5C/g, '\\');
        const relativeFilePath = decodedFilePath.replace(/^\/private/, '').replace(/\\/g, '/');
        const fullPath = path.join(privateFolderPath, path.normalize(relativeFilePath));

        // Check if the file exists
        if (fs.existsSync(fullPath)) {
            const fileName = path.basename(fullPath);
            res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
            res.sendFile(fullPath);
            console.log(`Downloading single file: ${fileName}`);
        } else {
            console.error(`File not found: ${fullPath}`);
            return res.status(404).send('File not found.');
        }
    } else {
        // If multiple files are selected, create a ZIP file
        const zip = archiver('zip', { zlib: { level: 9 } });

        // Set headers for downloading the ZIP file
        res.setHeader('Content-Type', 'application/zip');
        res.setHeader('Content-Disposition', 'attachment; filename=files.zip');

        zip.pipe(res); // Pipe the ZIP file to the response stream

        let filesAdded = 0;

        filePaths.forEach(filePath => {
            console.log(`Processing file path: ${filePath}`);

            // Decode and normalize the file path
            const decodedFilePath = decodeURIComponent(filePath).replace(/%5C/g, '\\');
            const relativeFilePath = decodedFilePath.replace(/^\/private/, '').replace(/\\/g, '/');
            const fullPath = path.join(privateFolderPath, path.normalize(relativeFilePath));

            // Check if the file exists and append it to the ZIP file
            if (fs.existsSync(fullPath)) {
                zip.append(fs.createReadStream(fullPath), { name: path.basename(fullPath) });
                filesAdded++;
                console.log(`Added file to zip: ${relativeFilePath}`);
            } else {
                console.warn(`File not found: ${fullPath}`);
            }
        });

        // Finalize the ZIP file creation
        zip.finalize();

        // Handle errors during ZIP creation
        zip.on('error', (err) => {
            console.error('Error creating ZIP file:', err);
            res.status(500).send('Error creating ZIP file.');
        });

        // Check if no files were added to the ZIP
        zip.on('end', () => {
            if (filesAdded === 0) {
                console.error('No valid files found to add to the ZIP.');
                res.status(404).send('No valid files found.');
            }
        });
    }
});

module.exports = router;