import uuid

from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone


class Ticket(models.Model):
    class Category(models.TextChoices):
        TECHNICAL = "technical", "Technical"
        BILLING = "billing", "Billing"
        ACCESS = "access", "Access"
        GENERAL = "general", "General"

    class Priority(models.TextChoices):
        LOW = "low", "Low"
        NORMAL = "normal", "Normal"
        HIGH = "high", "High"
        URGENT = "urgent", "Urgent"

    class Status(models.TextChoices):
        NEW = "new", "New"
        TRIAGE = "triage", "In triage"
        WAITING = "waiting", "Waiting on requester"
        RESOLVED = "resolved", "Resolved"

    public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    requester_name = models.CharField(max_length=120)
    requester_email = models.EmailField()
    subject = models.CharField(max_length=180)
    description = models.TextField()
    category = models.CharField(max_length=24, choices=Category.choices, default=Category.GENERAL)
    priority = models.CharField(max_length=16, choices=Priority.choices, default=Priority.NORMAL)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.NEW)
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="assigned_tickets",
    )
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-updated_at", "-created_at"]
        indexes = [
            models.Index(fields=["status", "priority"]),
            models.Index(fields=["created_at"]),
            models.Index(fields=["public_id"]),
        ]

    def __str__(self):
        return f"#{self.pk or 'new'} {self.subject}"

    def get_absolute_url(self):
        return reverse("ticket_detail", kwargs={"public_id": self.public_id})

    @property
    def ticket_number(self):
        if not self.pk:
            return "SUP-new"
        return f"SUP-{self.pk:04d}"

    @property
    def is_open(self):
        return self.status != self.Status.RESOLVED


class TicketReply(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name="replies")
    author_name = models.CharField(max_length=120)
    author_email = models.EmailField(blank=True)
    author_user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="ticket_replies",
    )
    body = models.TextField()
    is_staff_reply = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        return f"Reply by {self.author_name} on {self.ticket.ticket_number}"
