from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class ApparelItem(models.Model):
    """Generic configurable merchandise/apparel item for distribution at events."""
    name = models.CharField(max_length=255, help_text='e.g. "ICTAZ AGM 2025 T-Shirts", "Goodie Bags"')
    description = models.TextField(blank=True)
    event = models.ForeignKey(
        'events.Event', on_delete=models.SET_NULL,
        null=True, blank=True, related_name='apparel_items',
        help_text='Optional: link to the event this item is distributed at'
    )
    is_active = models.BooleanField(default=True, help_text='Only active items appear in the scanner')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Apparel Item'
        verbose_name_plural = 'Apparel Items'

    def __str__(self):
        return self.name

    @property
    def collection_count(self):
        return self.collections.count()


class CollectionRecord(models.Model):
    """Records that a paid member has collected an apparel item — via barcode scan."""
    apparel_item = models.ForeignKey(ApparelItem, on_delete=models.CASCADE, related_name='collections')
    registration_code = models.CharField(max_length=100, db_index=True)
    full_name = models.CharField(max_length=255)
    email = models.EmailField(blank=True)
    payment_status = models.CharField(max_length=100, blank=True)
    collected_at = models.DateTimeField(default=timezone.now)
    recorded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    notes = models.TextField(blank=True)

    class Meta:
        unique_together = ['apparel_item', 'registration_code']
        ordering = ['-collected_at']
        verbose_name = 'Collection Record'
        verbose_name_plural = 'Collection Records'

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