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

const addData = async (req, res) => {
  try {
    const client = req.params.client;
    const { tableName, data } = req.body;
    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 insertQuery = `
      INSERT INTO ${dBtableName} (id, data) VALUES ($1, $2)
      ON CONFLICT (id) DO UPDATE SET data = $2`;
    
    for (item of data) {
      await query(insertQuery, [item.id, item]);
    }

    res.status(200).json({ message: "Data added successfully" });

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

module.exports = addData;
