import uuid
from odoo import models, fields, api


class EncoachCode(models.Model):
    _name = "encoach.code"
    _description = "EnCoach Registration Code"

    code = fields.Char(required=True, index=True, default=lambda self: uuid.uuid4().hex[:8].upper())
    entity_id = fields.Many2one("encoach.entity", ondelete="set null")
    creator_id = fields.Many2one("res.users", required=True)
    expiry_date = fields.Datetime()
    code_type = fields.Selection(
        [("individual", "Individual"), ("corporate", "Corporate")],
        default="individual",
    )
    max_uses = fields.Integer(default=1)
    uses = fields.Integer(default=0)
    user_type = fields.Selection(
        [
            ("student", "Student"),
            ("teacher", "Teacher"),
            ("corporate", "Corporate"),
        ],
        default="student",
    )
    legacy_id = fields.Char(index=True)

    @api.model
    def validate_code(self, code_str):
        rec = self.search([("code", "=", code_str)], limit=1)
        if not rec:
            return {"valid": False, "error": "Code not found"}
        if rec.expiry_date and rec.expiry_date < fields.Datetime.now():
            return {"valid": False, "error": "Code expired"}
        if rec.max_uses and rec.uses >= rec.max_uses:
            return {"valid": False, "error": "Code fully used"}
        return {
            "valid": True,
            "code": rec.to_encoach_dict(),
        }

    def to_encoach_dict(self):
        self.ensure_one()
        return {
            "id": self.id,
            "code": self.code,
            "entity": self.entity_id.id if self.entity_id else None,
            "creator": self.creator_id.id,
            "expiryDate": (
                self.expiry_date.isoformat() if self.expiry_date else None
            ),
            "type": self.code_type,
            "maxUses": self.max_uses,
            "uses": self.uses,
            "userType": self.user_type,
        }
