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

const addTable = async (req, res) => {
  try {
    const { tableName } = req.body;
    const dBtableName = 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(409).json({ error: `Table ${tableName} already exists.` });
    }
    
    await query(`
      CREATE TABLE IF NOT EXISTS ${dBtableName} (
        id text primary key,
        created_at timestamp with time zone not null default now(),
        updated_at timestamp with time zone not null default now(),
        data jsonb not null)`);
    
    await query(`
      CREATE OR REPLACE TRIGGER set_update_${dBtableName}
        BEFORE UPDATE ON ${dBtableName}
        FOR EACH ROW
        EXECUTE PROCEDURE trigger_set_timestamp()`);

    res.status(200).json({ message: "Table created successfully" });

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

module.exports = addTable;
