const fs = require('fs');
const zlib = require('zlib');

const getDataWithinRange = (req, res) => {
    const { tableName, from, to } = req.params;
    const jsonFile = `./data/${tableName}.json.gz`;

    try {
        // Check if the compressed JSON file exists and load the existing data
        if (fs.existsSync(jsonFile)) {
            const compressedData = fs.readFileSync(jsonFile);
            const decompressedData = zlib.gunzipSync(compressedData);
            const jsonData = JSON.parse(decompressedData);

            // Filter the data based on the provided date/time range
            const filteredData = jsonData.filter(item => {
                const submittedDateStr = item['Request submitted date'];
                const submittedDate = new Date(submittedDateStr.replace(/-/g, '/')); // Convert to JavaScript Date object

                // Compare the submittedDate with the from and to dates
                return submittedDate >= new Date(from) && submittedDate <= new Date(to);
            });

            res.json(filteredData);
        } else {
            // If the file does not exist, return a 404 status code
            res.sendStatus(404);
        }
    } catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
};

module.exports = getDataWithinRange;
