from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import models
from customermanagement.models import Customer

Q6 = Decimal("0.000001")  # 6 decimal places

class CustomerField(models.Model):
    customer = models.ForeignKey(
        Customer,
        on_delete=models.CASCADE,
        related_name="fields",
        help_text="Field belongs to this customer."
    )
    field_name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)

    # ✅ 6-decimal GPS fields with clean defaults
    gps_lat = models.DecimalField(
        max_digits=9,
        decimal_places=6,
        null=True,
        blank=True
    )
    gps_long = models.DecimalField(
        max_digits=9,
        decimal_places=6,
        null=True,
        blank=True
    )

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

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["customer", "field_name"],
                name="uniq_field_name_per_customer",
            ),
        ]
        indexes = [models.Index(fields=["customer"])]
        ordering = ["-created_at"]

    def __str__(self):
        return self.field_name

    # ✅ Validation + rounding before save
    def clean(self):
        if self.gps_lat is not None:
            self.gps_lat = Decimal(self.gps_lat).quantize(Q6, rounding=ROUND_HALF_UP)
            if not (-90 <= float(self.gps_lat) <= 90):
                raise ValidationError({"gps_lat": "Latitude must be between -90 and 90."})

        if self.gps_long is not None:
            self.gps_long = Decimal(self.gps_long).quantize(Q6, rounding=ROUND_HALF_UP)
            if not (-180 <= float(self.gps_long) <= 180):
                raise ValidationError({"gps_long": "Longitude must be between -180 and 180."})

    def save(self, *args, **kwargs):
        if self.field_name:
            self.field_name = self.field_name.strip()
        self.full_clean()   # runs clean() + built-in validators
        return super().save(*args, **kwargs)
