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


class ContactStatus(models.TextChoices):
    UNREAD = "unread", "Unread"
    READ = "read", "Read"
    REPLIED = "replied", "Replied"
    ARCHIVED = "archived", "Archived"
    SPAM = "spam", "Spam"


class ContactCategory(models.TextChoices):
    GENERAL = "general", "General Inquiry"
    ADMISSION = "admission", "Admission"
    ACADEMICS = "academics", "Academics"
    FACILITIES = "facilities", "Facilities"
    COMPLAINT = "complaint", "Complaint"
    FEEDBACK = "feedback", "Feedback"
    OTHER = "other", "Other"


class ContactMessage(BaseModel):
    full_name = models.CharField(max_length=255)
    email = models.EmailField()
    phone = models.CharField(max_length=20, blank=True)

    category = models.CharField(
        max_length=20, choices=ContactCategory.choices, default=ContactCategory.GENERAL
    )
    subject = models.CharField(max_length=255, blank=True)
    message = models.TextField()

    status = models.CharField(
        max_length=20, choices=ContactStatus.choices, default=ContactStatus.UNREAD
    )
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="assigned_contacts",
    )
    admin_notes = models.TextField(blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)

    def __str__(self):
        return f"{self.full_name}: {self.subject}"

    class Meta:
        ordering = ["-created_at"]


class ContactReply(BaseModel):
    """Admin replies to contact messages (thread)."""

    message = models.ForeignKey(
        ContactMessage, on_delete=models.CASCADE, related_name="replies"
    )
    replied_by = models.ForeignKey(
        "users.User", on_delete=models.SET_NULL, null=True
    )
    body = models.TextField()
    sent_via_email = models.BooleanField(default=False)

    def __str__(self):
        return f"Reply to {self.message} by {self.replied_by}"

    class Meta:
        ordering = ["created_at"]
