const Role = require('../models/Role'); // Import Role model
const Permission = require('../models/Permission'); // Import Role model


exports.createRole = async (req, res) => {
  try {
    // Extract data from the request body
    const { roleName, permissionNames } = req.body;

    // Log the received data for debugging
    console.log('Request Body:', req.body);

    // Fetch permissions by their names
    const permissions = await Permission.find({ name: { $in: permissionNames } });

    if (permissions.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'No matching permissions found.',
      });
    }

    // Create a new role
    const role = new Role({
      name: roleName,
      permission: permissions.map((p) => p._id), // Extract ObjectIds from permissions
    });

    // Save the role to the database
    await role.save();

    console.log('Role created successfully:', role);

    // Return a JSON response with the created role
    return res.status(201).json({
      success: true,
      message: 'Role created successfully.',
      data: role,
    });
  } catch (error) {
    console.error('Error creating role:', error.message);

    // Handle errors and return a JSON response
    return res.status(500).json({
      success: false,
      message: 'An error occurred while creating the role.',
      error: error.message,
    });
  }
};




exports.getAllRoles = async (req, res) => {
  try {
    const roles = await Role.find().populate('permission'); // Populate permissions for roles
    res.status(200).json(roles);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching roles', error: error.message });
  }
};


exports.updateRole = async (req, res) => {
    const { id } = req.params; // Extract `id` from route parameters
    const { permissionNames } = req.body; // Extract `permissionNames` from the request body
  
  
    try {
      // Fetch permissions by name
      const permissions = await Permission.find({ name: { $in: permissionNames } });
  
      // Update the role
      const updatedRole = await Role.findByIdAndUpdate(
        id,
        { permission: permissions.map((p) => p._id) },
        { new: true }
      );
  
      if (!updatedRole) {
        return res.status(404).json({ message: 'Role not found' });
      }
  
      res.status(200).json({ message: 'Role updated successfully', role: updatedRole });
    } catch (error) {
      res.status(500).json({ message: 'Error updating role', error: error.message });
    }
  };
  
