const { query } = require("../config/database");

// Whitelist of allowed table names to prevent SQL injection
const ALLOWED_TABLES = [
  "products",
  "product_images",
  "portfolioprojects",
  "blogposts",
  "pages",
  "adminusers",
  "roles",
  "uploads",
  "media_folders",
  "team_members",
  "site_settings",
  "session",
];

// Validate table name against whitelist
const validateTableName = (table) => {
  if (!ALLOWED_TABLES.includes(table)) {
    throw new Error(`Invalid table name: ${table}`);
  }
  return table;
};

const buildSelectQuery = (
  table,
  conditions = [],
  orderBy = "createdat DESC"
) => {
  validateTableName(table);
  const whereClause =
    conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
  return `SELECT * FROM ${table} ${whereClause} ORDER BY ${orderBy}`;
};

const getById = async (table, id) => {
  validateTableName(table);
  const result = await query(`SELECT * FROM ${table} WHERE id = $1`, [id]);
  return result.rows[0] || null;
};

const getAllActive = async (table, orderBy = "createdat DESC") => {
  validateTableName(table);
  const result = await query(
    `SELECT * FROM ${table} WHERE isactive = true ORDER BY ${orderBy}`
  );
  return result.rows;
};

const deleteById = async (table, id) => {
  validateTableName(table);
  const result = await query(
    `DELETE FROM ${table} WHERE id = $1 RETURNING id`,
    [id]
  );
  return result.rowCount > 0;
};

const countRecords = async (table, condition = "") => {
  validateTableName(table);
  const whereClause = condition ? `WHERE ${condition}` : "";
  const result = await query(`SELECT COUNT(*) FROM ${table} ${whereClause}`);
  return parseInt(result.rows[0].count);
};

module.exports = {
  buildSelectQuery,
  getById,
  getAllActive,
  deleteById,
  countRecords,
  validateTableName,
};
