const pool = require("../config/db");

const getAllRoles = async () => {
  try {
    const [rows] = await pool.query('SELECT * FROM roles');
    return rows;
  } catch (error) {
    console.error('Error in getAllRoles:', error);
    throw error;
  }
};

const getRoleById = async (id) => {
  const [rows] = await pool.query('SELECT * FROM roles WHERE role_id = ?', [id]);
  return rows.length ? rows[0] : null;
};

const createRole = async (role_id, role_name, description) => {
  await pool.query('INSERT INTO roles (role_id, role_name, description) VALUES (?, ?, ?)', [role_id, role_name, description]);
};

const updateRole = async (id, role_name, description) => {
  const [result] = await pool.query('UPDATE roles SET role_name = ?, description = ? WHERE role_id = ?', [role_name, description, id]);
  return result.affectedRows > 0;
};

const deleteRole = async (id) => {
  const [result] = await pool.query('DELETE FROM roles WHERE role_id = ?', [id]);
  return result.affectedRows > 0;
};

module.exports = {
  getAllRoles,
  getRoleById,
  createRole,
  updateRole,
  deleteRole
};

