from django.db import models
from django.conf import settings
from category.models import Category
import random
import string

def _generate_request_id():
    return f"SR-{random.randint(0, 999999):06d}"

class ServiceRequest(models.Model):
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('confirmed', 'Confirmed'),
        ('assigned', 'Assigned'),
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
    ]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='service_requests')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='service_requests')
    
    request_id = models.CharField(max_length=16, unique=True, null=True, blank=True)
    
    service_date = models.DateField()
    service_time = models.CharField(max_length=64)

    contact_name = models.CharField(max_length=255, default="")
    contact_mobile = models.CharField(max_length=32, default="")
    
    # Service address stored as JSON
    service_address = models.JSONField(default=dict, blank=True)
    
    # Geo location
    geo_location = models.JSONField(default=dict, blank=True)
    
    # Items/Services requested (e.g. [{"name": "Sofa", "price": 500, "qty": 1}])
    items = models.JSONField(default=list, blank=True)
    
    total_price = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    
    notes = models.TextField(blank=True, null=True)
    
    trash = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.request_id} - {self.category} - {self.status}"

    def save(self, *args, **kwargs):
        if not self.request_id:
            for _ in range(10):
                candidate = _generate_request_id()
                if not self.__class__.objects.filter(request_id=candidate).exists():
                    self.request_id = candidate
                    break
            if not self.request_id:
                self.request_id = _generate_request_id()
        super().save(*args, **kwargs)
