# maintenance/models.py

from django.db import models
from django.conf import settings
from properties.models import Unit  # ✅ REQUIRED

User = settings.AUTH_USER_MODEL


class Complaint(models.Model):
    CATEGORY_CHOICES = (
        ('plumbing', 'Plumbing'),
        ('electricity', 'Electricity'),
        ('security', 'Security'),
        ('other', 'Other'),
    )

    STATUS_CHOICES = (
        ('open', 'Open'),
        ('in_progress', 'In Progress'),
        ('resolved', 'Resolved'),
    )

    tenant = models.ForeignKey(User, on_delete=models.CASCADE, related_name='complaints')
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='complaints')  # ✅ NEW

    category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    description = models.TextField()

    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='open')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)  # ✅ NEW

    class Meta:
        ordering = ['-created_at']  # ✅ NEW

    def __str__(self):
        return f"{self.tenant} - {self.category}"


class RepairRequest(models.Model):
    STATUS_CHOICES = (
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('completed', 'Completed'),
    )

    tenant = models.ForeignKey(User, on_delete=models.CASCADE, related_name='repair_requests')
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='repairs')  # ✅ NEW

    complaint = models.ForeignKey(
        Complaint,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='repairs'
    )  # ✅ LINK TO COMPLAINT

    issue = models.TextField()
    image = models.ImageField(upload_to='repairs/', null=True, blank=True)

    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')

    cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)  # ✅ NEW

    class Meta:
        ordering = ['-created_at']  # ✅ NEW

    def __str__(self):
        return f"Repair #{self.id} - {self.status}"