from django.db import models
from usermanagement.models import UserProfile
from products.models import Product
from cropmanagement.models import Crop

class ProductCropMapping(models.Model):
    product = models.ForeignKey(
        Product, on_delete=models.CASCADE, related_name='crop_mappings'
    )
    crop = models.ForeignKey(
        Crop, on_delete=models.CASCADE, related_name='product_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_product_crop_mappings',
        null=True, blank=True
    )
    updated_user = models.ForeignKey(
        UserProfile, on_delete=models.PROTECT,
        related_name='updated_product_crop_mappings',
        null=True, blank=True
    )

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

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