from django.db import models
from apps.events.models import Event


class CPDConfiguration(models.Model):
    event = models.OneToOneField(Event, on_delete=models.CASCADE, related_name='cpd_config')
    cpd_points = models.DecimalField(max_digits=5, decimal_places=2, default=0.0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'CPD Configuration'
        verbose_name_plural = 'CPD Configurations'

    def __str__(self):
        return f"{self.event.name} - {self.cpd_points} CPD Points"


class MembershipCache(models.Model):
    """Cache for membership system API lookups to improve performance"""
    national_id_type = models.CharField(max_length=20)
    national_id_no = models.CharField(max_length=50)
    
    # Cached membership data
    membership_number = models.CharField(max_length=50, blank=True)
    first_name = models.CharField(max_length=100, blank=True)
    middle_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    email = models.EmailField(blank=True)
    mobile = models.CharField(max_length=20, blank=True)
    
    # Cache metadata
    found_in_system = models.BooleanField(default=False)
    last_lookup = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = 'Membership Cache'
        verbose_name_plural = 'Membership Caches'
        unique_together = [['national_id_type', 'national_id_no']]
        indexes = [
            models.Index(fields=['national_id_type', 'national_id_no']),
            models.Index(fields=['last_lookup']),
        ]
    
    def __str__(self):
        return f"{self.national_id_type} {self.national_id_no} - {self.membership_number or 'Not Found'}"
