const express = require('express');
const fs = require('fs');
const path = require('path');
const util = require('util');

const router = express.Router();
const readdir = util.promisify(fs.readdir);
const stat = util.promisify(fs.stat);
const basePath = path.join(__dirname, '../private');
const folderPath = path.join(__dirname, '../private');

// List files with optional filter (recursive)
const getFilesRecursive = async (dir, filter, relativePath = '') => {
    let files = [];
    const items = await readdir(dir, { withFileTypes: true });

    for (const item of items) {
        const itemFullPath = path.join(dir, item.name);
        const itemRelativePath = path.join(relativePath, item.name);

        if (item.isDirectory()) {
            files = files.concat(await getFilesRecursive(itemFullPath, filter, itemRelativePath));
        } else if (item.isFile()) {
            if (!filter || filter.split(',').some(ext =>
                item.name.toLowerCase().endsWith(`.${ext.toLowerCase()}`)
            )) {
                files.push({
                    fullPath: itemFullPath,
                    relativePath: itemRelativePath
                });
            }
        }
    }
    return files;
};

router.get('/list', async (req, res) => {
    const filter = req.query.filter || '';
    const category = req.query.category || '';
    console.log(category);
    try {
        const searchPath = category ? path.join(basePath, category) : basePath;
        const foundFiles = await getFilesRecursive(searchPath, filter);

        const fileDetails = await Promise.all(foundFiles.map(async (file) => {
            const stats = await stat(file.fullPath);

            return {
                name: path.basename(file.relativePath),
                path: `/private/${encodeURIComponent(file.relativePath)}`,
                size: stats.size,
                createdAt: stats.birthtime,
                updatedAt: stats.mtime,
                category: category || path.dirname(file.relativePath) || 'root'
            };
        }));

        res.json(fileDetails);
    } catch (err) {
        console.error('Error fetching files:', err);
        res.status(500).send('Unable to fetch files');
    }
});

router.delete('/delete', async (req, res) => {
    const { fileName } = req.body;

    if (!fileName) {
        return res.status(400).send('File name not provided.');
    }

    try {
        let decodedFileName = decodeURIComponent(fileName);
        decodedFileName = decodedFileName.replace(/%5C/g, '\\');
        const relativeFilePath = decodedFileName.replace(/^\/private/, '').replace(/\\/g, '/');
        const filePath = path.join(folderPath, path.normalize(relativeFilePath));

        if (!fs.existsSync(filePath)) {
            return res.status(404).send(`File not found: ${fileName}`);
        }

        await fs.promises.unlink(filePath);
        res.status(200).send(`File deleted successfully: ${fileName}`);
    } catch (err) {
        console.error(`Error deleting file: ${err.message}`);
        res.status(500).send(`Error deleting file: ${fileName}`);
    }
});

module.exports = router;
