from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings


class User(AbstractUser):
    ROLE_CHOICES = [
        ('ADMIN', 'Admin'),
        ('STAFF', 'Staff'),
        ('CUSTOMER', 'Customer'),
        ('RIDER', 'Rider'),
    ]
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='CUSTOMER')
    banned = models.BooleanField(default=False)

    def __str__(self):
        return self.username


class Address(models.Model):
    """User address model — a user may have multiple addresses.

    Fields are optional so users can add them as needed.
    """
    ADDRESS_TYPE_CHOICES = [
        ('HOME', 'Home'),
        ('OFFICE', 'Office'),
        ('OTHER', 'Other'),
    ]

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='addresses',
    )
    address_type = models.CharField(max_length=10, choices=ADDRESS_TYPE_CHOICES, default='HOME')
    room_no = models.CharField(max_length=255, null=True, blank=True)
    street_address = models.TextField(null=True, blank=True)
    landmark = models.CharField(max_length=255, null=True, blank=True)
    city = models.CharField(max_length=255, null=True, blank=True)
    state = models.CharField(max_length=255, null=True, blank=True)
    zip_code = models.CharField(max_length=20, null=True, blank=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    trash = models.BooleanField(default=False)
    is_primary = models.BooleanField(default=False, help_text='Mark this address as the primary address for the user')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Address'
        verbose_name_plural = 'Addresses'

    def __str__(self):
        parts = [self.get_address_type_display()]
        if self.street_address:
            parts.append(self.street_address)
        elif self.city:
            parts.append(self.city)
        return " - ".join(parts)

    def save(self, *args, **kwargs):
        """Ensure only one primary address per user.

        If this instance is being saved with `is_primary=True`, clear the flag
        on other addresses belonging to the same user.
        """
        # If setting this address as primary, unset others first
        if self.is_primary:
            # Use the model's manager to update other addresses in a single query
            Address.objects.filter(user=self.user).exclude(pk=self.pk).update(is_primary=False)

        super().save(*args, **kwargs)
