from django.db import models

from cropmanagement.models import Crop
from usermanagement.models import UserProfile


class Scale(models.Model):
    scale_id = models.CharField(max_length=4, unique=True)
    description = models.CharField(max_length=255,null=True, blank=True)
    created_by = models.ForeignKey(
        UserProfile, null=True, blank=True, on_delete=models.CASCADE,
        related_name="scale_created_by"
    )
    updated_by = models.ForeignKey(
        UserProfile, null=True, blank=True, on_delete=models.CASCADE,
        related_name="scale_updated_by"
    )
    created_At = models.DateTimeField(auto_now_add=True)
    updated_At = models.DateTimeField(auto_now=True)    
    def __str__(self):
        return f"{self.scale_id}"

class ScaleCropMapping(models.Model):
    scale = models.ForeignKey(
        Scale, on_delete=models.CASCADE, related_name='scalecrop_mappings'
    )
    crop = models.ForeignKey(
        Crop, on_delete=models.CASCADE, related_name='scale_mappings'
    )
    scale_order_number = models.CharField(max_length=10)
    universal_moisture_threshold = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True
    )

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

    created_user = models.ForeignKey(
        UserProfile, on_delete=models.PROTECT,
        related_name='created_scale_crop_mappings',
        null=True, blank=True
    )
    updated_user = models.ForeignKey(
        UserProfile, on_delete=models.PROTECT,
        related_name='updated_scale_crop_mappings',
        null=True, blank=True
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['scale', 'crop'], name='unique_scale_crop_pair'
            )
        ]

    def __str__(self):
        return f"{self.scale.scale_id} ↔ {self.crop.name}"
