from odoo import models, fields, api


class EncoachEntity(models.Model):
    _name = 'encoach.entity'
    _description = 'EnCoach Entity'
    _inherit = ['mail.thread']

    name = fields.Char(required=True, tracking=True)
    code = fields.Char(required=True, tracking=True)
    type = fields.Selection([
        ('corporate', 'Corporate'),
        ('university', 'University'),
        ('school', 'School'),
        ('government', 'Government'),
        ('freelance', 'Freelance'),
    ], tracking=True)
    logo = fields.Binary(attachment=True)
    logo_url = fields.Char(string='Logo URL')
    primary_color = fields.Char(default='#4F46E5')
    secondary_color = fields.Char(default='#7C3AED')
    background_color = fields.Char(default='#FFFFFF')
    white_label_domain = fields.Char(string='White Label Domain')
    login_title = fields.Char()
    login_description = fields.Text()
    favicon = fields.Binary(attachment=True)
    results_release_mode = fields.Selection([
        ('auto', 'Auto'),
        ('manual_approval', 'Manual Approval'),
    ], default='auto')
    active = fields.Boolean(default=True)
    user_ids = fields.Many2many('res.users', 'encoach_entity_user_rel', 'entity_id', 'user_id', string='Users')
    role_ids = fields.One2many('encoach.role', 'entity_id', string='Roles')
    user_count = fields.Integer(compute='_compute_user_count', store=True)

    _code_unique = models.Constraint('UNIQUE(code)', 'Entity code must be unique.')

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

    def to_api_dict(self):
        self.ensure_one()
        return {
            'id': self.id,
            'name': self.name,
            'code': self.code,
            'type': self.type or '',
            'logo': bool(self.logo),
            'logo_url': self.logo_url or '',
            'primary_color': self.primary_color or '#4F46E5',
            'secondary_color': self.secondary_color or '#7C3AED',
            'background_color': self.background_color or '#FFFFFF',
            'white_label_domain': self.white_label_domain or '',
            'login_title': self.login_title or '',
            'login_description': self.login_description or '',
            'has_favicon': bool(self.favicon),
            'results_release_mode': self.results_release_mode or 'auto',
            'active': self.active,
            'user_count': self.user_count,
        }
