from django.db import models
from django.conf import settings

class Skill(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True, default='')
    color = models.CharField(max_length=20, default='#3b82f6')
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, default='')
    location = models.CharField(max_length=200, blank=True, default='')
    start_date = models.DateField()
    end_date = models.DateField()
    is_active = models.BooleanField(default=True, help_text="Aktiv/Deaktiviert Status")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='created_events')
    co_managers = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='managed_events', help_text="Weitere Verwalter dieser Veranstaltung")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def is_user_manager_or_admin(self, user):
        if not user or not user.is_authenticated:
            return False
        if user.is_admin_user or user.is_staff or user.is_superuser:
            return True
        if self.created_by_id == user.id:
            return True
        return self.co_managers.filter(id=user.id).exists()

    def __str__(self):
        return f"{self.title} ({'Aktiv' if self.is_active else 'Deaktiviert'})"

class TaskArea(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='task_areas')
    name = models.CharField(max_length=150)  # e.g., Tresendienst, Essen kochen, Aufbau, Aufräumen
    description = models.TextField(blank=True, default='')
    order = models.IntegerField(default=0)

    class Meta:
        ordering = ['order', 'id']

    def __str__(self):
        return f"{self.event.title} - {self.name}"

class Shift(models.Model):
    task_area = models.ForeignKey(TaskArea, on_delete=models.CASCADE, related_name='shifts')
    title = models.CharField(max_length=150)  # e.g., "Frühschicht", "14:00 - 18:00"
    date = models.DateField(null=True, blank=True, help_text="Spezifisches Datum für mehrtägige Veranstaltungen")
    start_time = models.CharField(max_length=50)  # e.g. "14:00" or ISO string
    end_time = models.CharField(max_length=50)    # e.g. "18:00" or ISO string
    max_participants = models.PositiveIntegerField(default=1)
    required_skills = models.ManyToManyField(Skill, blank=True, related_name='shifts')

    def __str__(self):
        date_str = f" ({self.date.strftime('%d.%m.%Y')})" if self.date else ""
        return f"{self.task_area.name}: {self.title}{date_str} ({self.start_time} - {self.end_time})"

class ShiftSignup(models.Model):
    shift = models.ForeignKey(Shift, on_delete=models.CASCADE, related_name='signups')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='shift_signups')
    guest_name = models.CharField(max_length=150, null=True, blank=True)
    guest_session_key = models.CharField(max_length=255, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']

    def __str__(self):
        if self.user:
            return f"{self.user.display_name or self.user.username} -> {self.shift.title}"
        return f"Gast: {self.guest_name} -> {self.shift.title}"

class EventTemplate(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(blank=True, default='')
    template_data = models.JSONField(help_text="JSON structure containing task areas and shifts")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='event_templates')
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name
