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


class CalendarEvent(models.Model):
    class EventType(models.TextChoices):
        MEETING = "meeting", "Meeting"
        WORKSHOP = "workshop", "Workshop"
        CONFERENCE = "conference", "Conference"
        DEADLINE = "deadline", "Deadline"
        LEAVE = "leave", "Staff leave"
        TRAVEL = "travel", "Travel"
        PUBLIC_HOLIDAY = "public_holiday", "Public holiday"
        OTHER = "other", "Other"

    class Visibility(models.TextChoices):
        PUBLIC = "public", "All staff"
        PRIVATE = "private", "Invite only"

    title = models.CharField(max_length=255)
    event_type = models.CharField(max_length=20, choices=EventType.choices, default=EventType.OTHER)
    description = models.TextField(blank=True)
    location = models.CharField(max_length=255, blank=True)
    start_datetime = models.DateTimeField()
    end_datetime = models.DateTimeField()
    all_day = models.BooleanField(default=False)
    visibility = models.CharField(max_length=10, choices=Visibility.choices, default=Visibility.PUBLIC)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="calendar_events_created",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["start_datetime"]
        indexes = [
            models.Index(fields=["start_datetime", "end_datetime"]),
        ]

    def __str__(self):
        return f"{self.title} ({self.start_datetime:%Y-%m-%d})"


class EventAttendee(models.Model):
    class ResponseStatus(models.TextChoices):
        INVITED = "invited", "Invited"
        ACCEPTED = "accepted", "Accepted"
        DECLINED = "declined", "Declined"
        TENTATIVE = "tentative", "Tentative"

    event = models.ForeignKey(CalendarEvent, on_delete=models.CASCADE, related_name="attendees")
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="calendar_invitations",
    )
    response = models.CharField(
        max_length=10, choices=ResponseStatus.choices, default=ResponseStatus.INVITED
    )
    responded_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        unique_together = [("event", "user")]
        ordering = ["user__last_name"]

    def __str__(self):
        return f"{self.user} @ {self.event}"
