const Role = require("../models/roleModel");


// GET permissions using role name
const getRolePermissions = async (req, res) => {
    try {

        const { role } = req.params;

        const roleDoc = await Role.findOne({
            name: role,
            isActive: true
        });

        if (!roleDoc) {
            return res.status(404).json({
                success: false,
                message: "Role not found"
            });
        }

        res.json({
            success: true,
            role: roleDoc.name,
            permissions: roleDoc.permissions
        });

    } catch (error) {

        res.status(500).json({
            success: false,
            message: error.message
        });

    }
};



//  UPDATE permission using role name
const updatePermission = async (req, res) => {
    try {

        const { role, module, subModule, action, value } = req.body;

        const roleDoc = await Role.findOne({
            name: role,
            isActive: true
        });

        if (!roleDoc) {
            return res.status(404).json({
                success: false,
                message: "Role not found"
            });
        }


        // find permission
        // let permission = roleDoc.permissions.find(
        //   p =>
        //     p.module === module &&
        //     (p.subModule || null) === (subModule || null)
        // );
        const normalizedModule = module?.toLowerCase();
        const normalizedSubModule = subModule
            ? subModule.toLowerCase()
            : null;

        let permission = roleDoc.permissions.find(p => {

            const dbModule = p.module?.toLowerCase();
            const dbSubModule = p.subModule
                ? p.subModule.toLowerCase()
                : null;

            return (
                dbModule === normalizedModule &&
                dbSubModule === normalizedSubModule
            );
        });



        // create if not exists
        if (!permission) {

            permission = {
                module,
                subModule: subModule || null,
                view: false,
                add: false,
                edit: false,
                delete: false
            };

            roleDoc.permissions.push(permission);
        }


        // update permission
        permission[action] = value;

        roleDoc.updatedBy = req.user?._id || null;

        await roleDoc.save();


        res.json({
            success: true,
            message: "Permission updated successfully"
        });

    } catch (error) {

        res.status(500).json({
            success: false,
            message: error.message
        });

    }
};


// GET /api/roles
const getAllRoles = async (req, res) => {
  const roles = await Role.find({ isActive: true }).select("name");
  res.json({ success: true, data: roles });
};


module.exports = {
    getRolePermissions,
    updatePermission,
    getAllRoles,
}