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

const updateData = async (req, res) => {
  try {
    const { tableName, data } = req.body;
    const { id } = req.params;
    const dBtableName = toSnakeCase(tableName);

    if (data.id != id) {
      return res.status(400).json({ message: "Error: id in payload not matching id in URL." });
    }

    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 findQuery = `SELECT data FROM ${dBtableName} WHERE id = $1`;
    const result = await query(findQuery, [id]);
    
    if (result.rows[0].data) {
      const updateQuery = `UPDATE ${dBtableName} SET data = $1 WHERE id = $2`;
      await query(updateQuery, [data, data.id]);
      res.status(200).json({ message: "Data updated successfully" });
    } else {
      res.status(404).json({ message: "Not found." });
    }

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

module.exports = updateData;
