from django.db import models
from django.utils import timezone
import secrets


class InvitationCode(models.Model):
    code = models.CharField(max_length=32, unique=True, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField()
    is_used = models.BooleanField(default=False)
    used_by = models.OneToOneField(
        'reymotausers.ReyMotaUser',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='used_invitation'
    )
    created_by = models.ForeignKey(
        'reymotausers.ReyMotaUser',
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_invitations'
    )

    class Meta:
        verbose_name = "Código de Invitación"
        verbose_name_plural = "Códigos de Invitación"

    def __str__(self):
        return f"{self.code} (expira: {self.expires_at:%d/%m/%Y %H:%M})"

    @classmethod
    def generate_code(cls):
        while True:
            code = secrets.token_urlsafe(24)[:32]
            if not cls.objects.filter(code=code).exists():
                return code

    @classmethod
    def create_invitation(cls, created_by=None, hours_valid=24):
        expires_at = timezone.now() + timezone.timedelta(hours=hours_valid)
        return cls.objects.create(
            code=cls.generate_code(),
            expires_at=expires_at,
            created_by=created_by
        )

    def is_valid(self):
        if self.is_used or self.expires_at is None:
            return False
        return timezone.now() < self.expires_at

    def mark_as_used(self, user):
        self.is_used = True
        self.used_by = user
        self.save()