from django.db import models
from shop_management.models.base import DataRoot
from django.contrib.auth.models import User
from shop_management.models.data.shop import Shop
from shop_management.models.data.utils import Currency, Unit


# Optional: a Category model for organizing products within a shop.
class Category(DataRoot):
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='category')
    name = models.CharField(max_length=100)
    description = models.TextField(null=True,blank=True)

    def __str__(self):
        return self.name
    
    
    
    
# A Product model that holds details about each product.
class Product(DataRoot):
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='products')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products')
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=100, null=True, blank=True)
    barcode = models.CharField(max_length=100, null=True, blank=True, db_index=True)
    default_unit = models.ForeignKey(
        Unit,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="default_for_products",
    )
    minimum_stock_level = models.DecimalField(
        max_digits=18, decimal_places=4, default=0
    )
    requires_batch = models.BooleanField(default=False)
    requires_expiry = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    description = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='product_images/', blank=True, null=True)

    
    def __str__(self):
        return self.name


class ProductPrice(DataRoot):
    class PriceType(models.TextChoices):
        RETAIL = "RETAIL", "Sale"

    product = models.ForeignKey(
        Product, related_name="prices", on_delete=models.CASCADE
    )
    currency = models.ForeignKey(
        Currency, related_name="product_prices", on_delete=models.PROTECT
    )
    price_type = models.CharField(max_length=20, choices=PriceType.choices)
    amount = models.DecimalField(max_digits=18, decimal_places=4)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["product", "currency", "price_type"],
                name="uniq_product_currency_price_type",
            ),
            models.CheckConstraint(
                check=models.Q(amount__gte=0),
                name="product_price_nonnegative",
            ),
        ]
        ordering = ["product_id", "currency_id", "price_type"]

    def __str__(self):
        return f"{self.product} - {self.currency} - {self.get_price_type_display()}"
