from django.db import models
from common.models.base import TimeStampedModel
from producers_sub_categories.models.producers_sub_categories import ProducersSubCategories
from django.core.validators import MinValueValidator, MaxValueValidator
from api.property_api.city.models.city import City


class ProductsType(models.IntegerChoices):
    """
    ENUM types for different product

    """
    REGULAR = 1
    FLEA = 2

class ProducersProducts(TimeStampedModel):
    name = models.CharField(max_length=255)
    country = models.CharField(max_length=255,null=True, blank=True)
    state = models.CharField(max_length=255,null=True, blank=True)
    city = models.ForeignKey(City,on_delete=models.SET_NULL,blank=True,null=True)
    description = models.TextField()
    brand = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=20,decimal_places=2)
    sub_category = models.ForeignKey(ProducersSubCategories, on_delete=models.CASCADE,related_name="product_sub_category")
    products_type = models.IntegerField(choices=ProductsType, default=1)
    is_flag = models.BooleanField(default=False)
    contact_no = models.CharField(max_length=15,blank=True,null=True)

    class Meta:
        ordering = ['id']
        verbose_name_plural = 'Producers_products'

    def __str__(self):
        return self.name
    
    def soft_delete(self):
        if self.is_active:
            self.is_active = False
            self.save(update_fields=['is_active'])


class ProductsReview(TimeStampedModel):
    review_star = models.PositiveIntegerField(blank=True, validators=[MinValueValidator(1), MaxValueValidator(5)])
    message = models.TextField()
    review_image = models.CharField(max_length=255, blank=True, null=True, help_text="Cloudinary public_id for image")
    review_video = models.CharField(max_length=255, blank=True, null=True, help_text="Cloudinary public_id for video")
    video_duration = models.PositiveIntegerField(blank=True, null=True, help_text="Video duration in seconds")
    product = models.ForeignKey(ProducersProducts, on_delete=models.CASCADE, related_name='product_review')
    is_flagged_review = models.BooleanField(default=False, blank=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = 'products_reviews'
        constraints = [
            models.CheckConstraint(
                check=(
                    models.Q(review_image__isnull=False, review_video__isnull=True) |
                    models.Q(review_image__isnull=True, review_video__isnull=False) |
                    models.Q(review_image__isnull=True, review_video__isnull=True)
                ),
                name='product_review_image_or_video_not_both'
            )
        ]

    def soft_delete(self):
        if self.is_active:
            self.is_active = False
            self.save(update_fields=['is_active'])
