from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class SoftDeleteManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(deleted_at__isnull=True)


class State(models.Model):
    name = models.CharField(max_length=100, unique=True, verbose_name="اسم الولاية")
    code = models.CharField(max_length=10, unique=True, verbose_name="الكود")

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='state_created')
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='state_updated')
    deleted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='state_deleted')

    objects = SoftDeleteManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()

    def hard_delete(self):
        super().delete()

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "ولاية"
        verbose_name_plural = "الولايات"
        indexes = [
            models.Index(fields=['deleted_at']),
            models.Index(fields=['name']),
        ]


class Locality(models.Model):
    name = models.CharField(max_length=100, verbose_name="اسم المحلية")
    code = models.CharField(max_length=10, blank=True, null=True, verbose_name="الكود")
    state = models.ForeignKey(State, on_delete=models.PROTECT, related_name='localities', verbose_name="الولاية")

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='locality_created')
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='locality_updated')
    deleted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='locality_deleted')

    objects = SoftDeleteManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()

    def hard_delete(self):
        super().delete()

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

    class Meta:
        verbose_name = "محلية"
        verbose_name_plural = "المحليات"
        unique_together = ['name', 'state']
        indexes = [
            models.Index(fields=['deleted_at']),
            models.Index(fields=['name']),
        ]


class Area(models.Model):
    name = models.CharField(max_length=100, verbose_name="اسم المنطقة")
    code = models.CharField(max_length=10, blank=True, null=True, verbose_name="الكود")
    locality = models.ForeignKey(
        Locality,
        on_delete=models.PROTECT,
        related_name='areas',
        verbose_name="المحلية"
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='area_created')
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='area_updated')
    deleted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='area_deleted')

    objects = SoftDeleteManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()

    def hard_delete(self):
        super().delete()

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

    class Meta:
        verbose_name = "منطقة"
        verbose_name_plural = "المناطق"
        unique_together = ['name', 'locality']
        indexes = [
            models.Index(fields=['deleted_at']),
            models.Index(fields=['name']),
        ]


class Location(models.Model):
    ZONING_CHOICES = [
        ('commercial', 'تجارية'),
        ('residential', 'سكنية'),
        ('industrial', 'صناعية'),
        ('services', 'خدمية'),
        ('mixed', 'مختلطة'),
    ]

    name = models.CharField(max_length=100, verbose_name="اسم الموقع")
    code = models.CharField(max_length=10, blank=True, null=True, verbose_name="الكود")
    area = models.ForeignKey(
        Area,
        on_delete=models.PROTECT,
        related_name='locations',
        verbose_name="المنطقة"
    )
    zoning = models.CharField(
        max_length=20,
        choices=ZONING_CHOICES,
        blank=True,
        null=True,
        verbose_name="المنطقة التصنيفية"
    )
    latitude = models.DecimalField(
        max_digits=9, decimal_places=6, null=True, blank=True, verbose_name="خط العرض"
    )
    longitude = models.DecimalField(
        max_digits=9, decimal_places=6, null=True, blank=True, verbose_name="خط الطول"
    )

    # Audit fields
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    deleted_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='location_created')
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='location_updated')
    deleted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='location_deleted')

    objects = SoftDeleteManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()

    def hard_delete(self):
        super().delete()

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

    class Meta:
        verbose_name = "موقع"
        verbose_name_plural = "المواقع"
        unique_together = ['name', 'area']
        indexes = [
            models.Index(fields=['deleted_at']),
            models.Index(fields=['name']),
        ]