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

const router = express.Router();

// Helper function to recursively search files in directories
const searchFilesInDir = (dirPath, query, filesFound = []) => {
    const files = fs.readdirSync(dirPath);

    files.forEach(file => {
        const fullPath = path.join(dirPath, file);
        const stats = fs.statSync(fullPath);

        if (stats.isDirectory()) {
            // If it's a directory, recursively search inside it
            searchFilesInDir(fullPath, query, filesFound);
        } else {
            // If it's a file, check if it matches the query
            if (file.toLowerCase().includes(query)) {
                filesFound.push({
                    name: file,
                    path: `/private/${encodeURIComponent(path.relative(__dirname, fullPath))}`,
                    size: stats.size,
                    createdAt: stats.birthtime,
                    updatedAt: stats.mtime,
                });
            }
        }
    });
};

// Search files route
router.get('/', (req, res) => {
    const folderPath = path.join(__dirname, '../private');
    const query = req.query.q?.toLowerCase().trim() || '';

    console.log(`Received search query: ${query}`); // Log the query

    if (query.length < 2) {
        console.log('Query is too short'); // Log if query is too short
        return res.status(400).json({ error: 'Query must be at least 2 characters long.' });
    }

    try {
        const filesFound = [];
        searchFilesInDir(folderPath, query, filesFound);

        if (filesFound.length === 0) {
            console.log('No files found matching the query'); // Log if no files are found
            return res.status(404).json({ message: 'No files found matching the query.' });
        }

        console.log('Found files:', filesFound); // Log the found files
        res.json(filesFound);
    } catch (err) {
        console.error('Error during file search:', err); // Log any unexpected error
        return res.status(500).send('Unable to fetch files.');
    }
});

module.exports = router;