from odoo import fields, models


class HrEmployee(models.Model):
    _inherit = "hr.employee"

    xeno_module_access_ids = fields.One2many(
        "xeno.employee.module.access", "employee_id",
        string="Individual Module Access", groups="hr.group_hr_user")

    def _xeno_has_module_access(self, module_name):
        """Single resolution point for XENHR's System Access rule: group
        grant OR individual grant, HR/Admin always pass. module_name is
        matched case-insensitively against xeno.hr.module.name, mirroring
        XENHR's own canAccessModule() lookup. Callers that gate a
        self-service surface should call this rather than re-deriving
        group/individual logic themselves.

        Reads sudo() throughout: this is meant to be called from a
        regular employee's own request context once enforcement is wired
        in, and both xeno_module_access_ids and hr.employee.category's
        xeno_module_ids are groups="hr.group_hr_user" -- reading them as
        the acting employee would raise AccessError for every non-HR
        self-service user, the same class of bug already hit once in
        xeno_audit_log."""
        self.ensure_one()
        if self.user_id and (
            self.user_id.has_group("hr.group_hr_user")
            or self.user_id.has_group("base.group_system")
        ):
            return True
        emp = self.sudo()
        module = self.env["xeno.hr.module"].sudo().search(
            [("name", "=ilike", module_name), ("active", "=", True)], limit=1)
        if not module:
            return False
        if module in emp.category_ids.xeno_module_ids:
            return True
        access = emp.xeno_module_access_ids.filtered(
            lambda a: a.module_id == module)
        return bool(access and access[0].enabled)
