from django.db import models
from django.conf import settings
import uuid
from tenants.models import Tenants
from users.models import Users

# Define choices for the complaint status
STATUS_CHOICES = [
    ('received', 'Received'),
    ('pending', 'Pending'),
    ('closed', 'Closed'),
]

class ComplaintCategory(models.Model):
    """
    Represents a category or type of complaint, which can be
    specific to a tenant.
    """
    category_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, 
        on_delete=models.CASCADE, 
        related_name='complaint_categories'
    )
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} ({self.tenant.name})"

class Complaint(models.Model):
    """
    Represents a citizen's incident report.
    Includes support for multi-tenant data isolation.
    """
    complaint_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, 
        on_delete=models.CASCADE, 
        related_name='complaints'
    )
    user = models.ForeignKey(
        Users,
        on_delete=models.SET_NULL,
        null=True,
        related_name='complaints',
        editable=False  # This field should be set by the system, not directly by the user
    )
    category = models.ForeignKey(
        ComplaintCategory, 
        on_delete=models.SET_NULL, 
        null=True, 
        related_name='complaints'
    )
    short_description = models.CharField(max_length=255)
    status = models.CharField(
        max_length=20, 
        choices=STATUS_CHOICES, 
        default='received'
    )
    complaint_text = models.TextField()
    complaint_audio = models.FileField(upload_to='complaint_audio/', blank=True, null=True)
    complaint_video = models.FileField(upload_to='complaint_video/', blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Complaint {self.complaint_id} - {self.status}"

class ComplaintStatusHistory(models.Model):
    """
    Tracks changes to a complaint's status over time.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    complaint = models.ForeignKey(
        Complaint, 
        on_delete=models.CASCADE, 
        related_name='status_history'
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES)
    resolution_message = models.TextField(blank=True, null=True)
    changed_at = models.DateTimeField(auto_now_add=True)
    changed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )

    def __str__(self):
        return f"Status of Complaint {self.complaint.complaint_id} changed to '{self.status}'"
