const Role = require('../models/role');

exports.getRole = async (req, res) => {
    try {
      const roles = await Role.findAll();
      res.status(200).json(roles);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }

  };
  exports.getRoleByID = async (req, res) => {
    try {
      const role = await Role.findByPk(req.params.id);
      if (role) {
        res.status(200).json(role);
      } else {
        res.status(404).json({ error: 'Role not found' });
      }
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };
  
  exports.createRole = async (req, res) => {
    try {
      const { role_id, role_name } = req.body;
      const newrole = await Role.create({
        role_id,
        role_name,
      
      });
      res.status(201).json({ actionStatus: 'Success', message: 'Create Success!!', statusCode: 200, role: newrole });
    } catch (err) {
      res.status(400).json({ error: err.message });
    }
  };

  exports.updateRole = async (req, res) => {
    try {
        const { id } = req.params; 
        const {role_id, role_name } = req.body; 

       
        const role = await Role.findByPk(id);
        

        if (role) {
            
            role.role_id = role_id || role.role_id; 
            role.role_name = role_name || role.role_name; 
            role.updated_at = new Date(); 

           
            await role.save();

            res.status(200).json({
                actionStatus: 'Success',
                message: 'Update Success!!',
                statusCode: 200,
                role: role
            });
        } else {
            res.status(404).json({ error: 'Role not found' });
        }
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
  
  exports.deleteRole = async (req, res) => {
    try {
      const { id } = req.params;
  
      
      const role = await Role.findByPk(id);
  
      if (role) {
        
        await role.destroy();
        res.status(200).json({ actionStatus: 'Success', message: 'Delete Success!!', statusCode: 200 }); 
      } else {
        res.status(404).json({ error: 'Member not found' });
      }
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };
