from odoo import models, fields, api


class EncoachRole(models.Model):
    _name = "encoach.role"
    _description = "EnCoach Role"

    name = fields.Char(required=True)
    code = fields.Char(index=True)
    description = fields.Text()
    entity_id = fields.Many2one("encoach.entity", required=True, ondelete="cascade")
    permission_ids = fields.Many2many("encoach.permission", string="Permissions")
    user_ids = fields.Many2many(
        "res.users", "encoach_role_user_rel", "role_id", "user_id",
        string="Users",
    )
    is_default = fields.Boolean(default=False)
    legacy_id = fields.Char(index=True)
    user_count = fields.Integer(compute="_compute_user_count", store=True)

    @api.depends("user_ids")
    def _compute_user_count(self):
        for rec in self:
            rec.user_count = len(rec.user_ids)

    def to_encoach_dict(self):
        self.ensure_one()
        return {
            "id": self.id,
            "label": self.name,
            "entityID": self.entity_id.id,
            "permissions": [p.code for p in self.permission_ids if p.code],
            "isDefault": self.is_default,
        }
