// const Role = require("../models/roleModel");
const {pool} = require("../../config/db")

// 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 });
};












// new API'S

const getRoles = async (req, res) => {
    console.log('iuytytgufurtytftytftyftygu')
  try {
    const { rows } = await pool.query(`
      SELECT
        id,
        LOWER(role_name) AS role_name
      FROM roles
      WHERE is_active = true
        AND is_deleted = false
      ORDER BY role_name
    `);

    return res.status(200).json({
      success: true,
      count: rows.length,
      data: rows,
    });
  } catch (error) {
    console.error("GET ROLES ERROR:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch roles",
      error: error.message,
    });
  }
};


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