const asyncHandler = require('../middlewares/asyncHandler');
const {
  getAllRoles,
  getRoleById,
  createRole,
  updateRole,
  deleteRole
} = require('../repositories/rolesRepository');

// Get all roles
exports.getAllRoles = asyncHandler(async (req, res) => {
    try {
        const rows = await getAllRoles();
        res.status(200).json({ success: true, data: rows });
    } catch (error) {
        console.error('Error fetching roles:', error);
        throw error;
    }
});

// Get role by ID
exports.getRoleById = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const role = await getRoleById(id);
    
    if (!role) {
        return res.status(404).json({ success: false, message: 'Role not found' });
    }
    
    res.status(200).json({ success: true, data: role });
});

// Create role
exports.createRole = asyncHandler(async (req, res) => {
    const { role_id, role_name, description } = req.body;
    
    if (!role_id || !role_name) {
        return res.status(400).json({ success: false, message: 'role_id and role_name are required' });
    }
    
    await createRole(role_id, role_name, description);
    res.status(201).json({ success: true, message: 'Role created successfully' });
});

// Update role
exports.updateRole = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { role_name, description } = req.body;
    
    if (!role_name) {
        return res.status(400).json({ success: false, message: 'role_name is required' });
    }
    
    const updated = await updateRole(id, role_name, description);
    
    if (!updated) {
        return res.status(404).json({ success: false, message: 'Role not found' });
    }
    
    res.status(200).json({ success: true, message: 'Role updated successfully' });
});

// Delete role
exports.deleteRole = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const deleted = await deleteRole(id);
    
    if (!deleted) {
        return res.status(404).json({ success: false, message: 'Role not found' });
    }
    
    res.status(200).json({ success: true, message: 'Role deleted successfully' });
});

