const query = require("../db.js");
const fs = require('fs');
const zlib = require('zlib');
const { toSnakeCase } = require("./utils.js");

const getGzFile = async (req, res) => {
  try {
    const { client, tableName } = req.params;
    const dBtableName = `${client}_${toSnakeCase(tableName)}`;

    let data;

    // Check if table exists
    const tableCheck = await query(`
    SELECT EXISTS (SELECT 1 FROM pg_tables WHERE tablename = $1)
    AS table_exists`, [dBtableName]);
    if (!tableCheck.rows[0]["table_exists"]) {
      return res.status(404).json({ error: `Data collection ${tableName} not found.` });
    }

    // Get data and create the json file
    const result = await query(`SELECT data FROM ${dBtableName}`);
    if (result.rows.length > 0) {
      data = result.rows.map(row => row.data);
    } else {
      res.status(404).json({ message: "Not found." });
    }

    // Make json file
    const jsonFile = `./${tableName}.json.gz`;
    const compressedData = zlib.gzipSync(JSON.stringify(data));
    fs.writeFileSync(jsonFile, compressedData);

    // Deliver the json file
    if (fs.existsSync(jsonFile)) {
      const compressedData = fs.readFileSync(jsonFile);
      res.setHeader('Content-Type', 'application/gzip');
      res.setHeader('Content-Disposition', `attachment; filename=${tableName}.json.gz`);
      res.send(compressedData);
      fs.unlinkSync(jsonFile);
    } else {
      res.sendStatus(404);
    }
  } catch (err) {
    console.error("Error handling the request:", err);
    res
      .status(500)
      .json({ error: "An error occurred while processing the request" });
  }
}

module.exports = getGzFile;
