from odoo import api, fields, models


class XenoAttendanceViewer(models.Model):
    _name = "xeno.attendance.viewer"
    _description = "Configured 'My Team Attendance' viewer per HRSystem employee_code"
    _order = "employee_code"

    employee_code = fields.Char(
        required=True, index=True,
        help="HRSystem employee_code (see it on the Monthly Attendance "
             "report) whose attendance this user should see under "
             "'My Team Attendance'.")
    user_id = fields.Many2one("res.users", string="Viewer (manager)", required=True)
    note = fields.Char()
    active = fields.Boolean(default=True)

    def name_get(self):
        return [(r.id, "%s → %s" % (r.employee_code, r.user_id.name)) for r in self]

    @api.model
    def get_team_codes(self, user):
        rules = self.sudo().search([("user_id", "=", user.id), ("active", "=", True)])
        if rules:
            return rules.mapped("employee_code")
        # No manual curation configured for this manager -- rather than
        # silently showing an empty team (the bug reported for a manager
        # with a real, deep reporting line but zero rows here), fall back
        # to their actual org hierarchy: every employee under them,
        # recursively (subordinates' subordinates too), via hr.employee's
        # own manager_id chain. A manager who DOES have explicit rows
        # (e.g. susu's own curated 2-person list, which intentionally
        # isn't her literal reporting line) is untouched by this fallback.
        employee = self.env["hr.employee"].sudo().search(
            [("user_id", "=", user.id)], limit=1)
        if not employee:
            return []
        subordinates = self.env["hr.employee"].sudo().search(
            [("id", "child_of", employee.id)]) - employee
        return [c for c in subordinates.mapped("xeno_employee_code") if c]
