from odoo import models, fields, api

USER_TYPE_SELECTION = [
    ('student', 'Student'),
    ('teacher', 'Teacher'),
    ('admin', 'Admin'),
    ('corporate', 'Corporate'),
    ('mastercorporate', 'Master Corporate'),
    ('agent', 'Agent'),
    ('developer', 'Developer'),
]


class EncoachUser(models.Model):
    _inherit = 'res.users'

    user_type = fields.Selection(USER_TYPE_SELECTION, string='User Type')
    is_verified = fields.Boolean(default=False)
    entity_ids = fields.Many2many('encoach.entity', 'encoach_entity_user_rel', 'user_id', 'entity_id', string='Entities')
    phone = fields.Char()
    birth_date = fields.Date()
    gender = fields.Selection([('m', 'Male'), ('f', 'Female'), ('o', 'Other')])
    op_student_id = fields.Many2one('op.student', string='OpenEduCat Student')
    op_faculty_id = fields.Many2one('op.faculty', string='OpenEduCat Faculty')
    encoach_avatar = fields.Binary(attachment=True, string='EnCoach Avatar')
    last_login = fields.Datetime()
    role_ids = fields.Many2many(
        'encoach.role', 'encoach_role_user_rel', 'user_id', 'role_id', string='Roles',
    )
    permission_direct_ids = fields.Many2many(
        'encoach.permission', 'encoach_user_permission_rel', 'user_id', 'permission_id',
        string='Direct Permissions',
    )

    first_login = fields.Boolean(default=True)
    account_source = fields.Selection([
        ('self_registered', 'Self Registered'),
        ('entity_bulk_upload', 'Entity Bulk Upload'),
    ])
    account_status = fields.Selection([
        ('unactivated', 'Unactivated'),
        ('activated', 'Activated'),
        ('suspended', 'Suspended'),
    ], default='unactivated')

    def get_all_permissions(self):
        """Return the union of direct permissions and permissions from all assigned roles."""
        self.ensure_one()
        role_permissions = self.role_ids.mapped('permission_ids')
        return self.permission_direct_ids | role_permissions

    def _api_user_type(self):
        """Frontend routes require a non-empty role; many users have no encoach.user_type set yet."""
        self.ensure_one()
        if self.user_type:
            return self.user_type
        if self.op_faculty_id:
            return 'teacher'
        if self.op_student_id:
            return 'student'
        if self.has_group('base.group_system'):
            return 'admin'
        return ''

    def to_api_dict(self):
        self.ensure_one()
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email or '',
            'login': self.login or '',
            'user_type': self._api_user_type(),
            'is_verified': self.is_verified,
            'phone': self.phone or '',
            'birth_date': self.birth_date.isoformat() if self.birth_date else None,
            'gender': self.gender or '',
            'avatar': bool(self.encoach_avatar),
            'entities': [
                {'id': e.id, 'name': e.name, 'logo': bool(e.logo)}
                for e in self.entity_ids
            ],
            'last_login': self.last_login.isoformat() if self.last_login else None,
            'first_login': self.first_login,
            'account_source': self.account_source or '',
            'account_status': self.account_status or 'unactivated',
        }
