from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from .models import StockHistory
from categories.models import Product
from django.utils import timezone

@receiver(pre_save, sender=Product)
def store_previous_stock(sender, instance, **kwargs):
    try:
        # Menyimpan nilai stok sebelumnya
        instance._previous_stock = Product.objects.get(pk=instance.pk).qty
    except Product.DoesNotExist:
        # Jika produk baru
        instance._previous_stock = 0

@receiver(post_save, sender=Product)
def create_stock_history(sender, instance, created, **kwargs):
    current_stock = instance.qty
    previous_stock = getattr(instance, '_previous_stock', 0)
    
    # Hanya buat history jika ada penambahan stok
    if current_stock > previous_stock:
        stock_change = current_stock - previous_stock
        
        StockHistory.objects.create(
            product=instance,
            supplier=instance.supplier,
            stock_in=stock_change,
            date_in=timezone.now().date(),
            #notes=f"Automatic entry: Stock increased by {stock_change} units"
        )