from django.db import models
import uuid
import os
from django.utils.timezone import now
from .event import Event, Club

def image_upload_path(instance, filename):
    """Generate a unique file path for the uploaded image."""
    # Get the file extension from the original filename
    ext = filename.split('.')[-1]
    # Create a unique filename using UUID
    unique_filename = f"{uuid.uuid4().hex}.{ext}"

    if instance.event:
        # Determine the folder based on the event
        folder = f"event_{instance.event.id}"
    elif instance.club:
        folder = f"club_{instance.club.id}"
    else:
        folder = f"unknown"
    # Return the complete upload path
    return os.path.join('images', folder, unique_filename)

class Image(models.Model):
    """Model for storing uploaded images for events."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to=image_upload_path)
    uploaded_at = models.DateTimeField(default=now)

    # Relation to event model
    event = models.ForeignKey(Event, null=True, blank=True, on_delete=models.CASCADE, related_name='images')
    club = models.ForeignKey(Club, null=True, blank=True, on_delete=models.CASCADE, related_name='images')

    # Image type for filtering
    IMAGE_TYPES = (
        ('sponsor', 'Sponsor'),
        ('club', 'Club'),
    )
    image_type = models.CharField(max_length=20, choices=IMAGE_TYPES, default='sponsor')

    order = models.IntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.title or f"Event Image {self.id}"
