import uuid
import random
import string
from django.db import models
from django.utils import timezone


def generate_registration_code(length=6):
    characters = string.digits + string.ascii_uppercase
    while True:
        code = ''.join(random.choices(characters, k=length))
        if not Registration.objects.filter(registration_code=code).exists():
            return code


class Registration(models.Model):
    STATUS_CHOICES = (
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    )
    PAYMENT_STATUS_CHOICES = (
        ('not_required', 'Not Required'),
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    registration_code = models.CharField(max_length=20, unique=True, default=generate_registration_code)
    full_name = models.CharField(max_length=255)
    email = models.EmailField()
    phone = models.CharField(max_length=30, blank=True)
    organisation = models.CharField(max_length=255, blank=True)
    event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='registrations')
    status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='pending')
    payment_status = models.CharField(max_length=50, choices=PAYMENT_STATUS_CHOICES, default='not_required')
    has_attended = models.BooleanField(default=False)
    attendance_timestamp = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True)
    registered_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ['email', 'event']
        ordering = ['-registered_at']
        verbose_name = 'Registration'
        verbose_name_plural = 'Registrations'

    def __str__(self):
        return f'{self.full_name} — {self.event.name} ({self.registration_code})'

    def save(self, *args, **kwargs):
        if not self.pk:
            if self.event.is_paid:
                self.payment_status = 'pending'
            else:
                self.payment_status = 'not_required'
                self.status = 'approved'
        super().save(*args, **kwargs)


class PaymentProof(models.Model):
    registration = models.OneToOneField(Registration, on_delete=models.CASCADE, related_name='payment_proof')
    file = models.FileField(upload_to='payment_proofs/%Y/%m/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    notes = models.TextField(blank=True)
    reviewed = models.BooleanField(default=False)
    reviewed_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f'Payment proof for {self.registration}'
