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

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

    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.` });
    }
    
    const pageSize = 1000;
    const pageNumber = Number(page);
    const offset = (pageNumber - 1) * pageSize;

    // Determine total rows in table
    const result = await query(`SELECT COUNT(*) FROM ${dBtableName}`);
    const totalRows = result.rows[0].count;

    // Get page
    const result2 = await query(`
      SELECT data
      FROM ${dBtableName}
      ORDER BY id
      OFFSET $1 ROWS
      FETCH FIRST $2 ROWS ONLY`, [offset, pageSize]);

    const pageData = result2.rows.map(row => row.data);
    res.status(200).json({
      data: pageData,
      currentPage: pageNumber,
      totalPages: Math.ceil(totalRows / pageSize)
  });

  } catch (err) {
    console.error("Error handling the request:", err);
    res.status(500).json({ error: "An error occurred while processing the request" });
  }
};

module.exports = getAllData;
