# services/product_boosting.py

from product.models import Product 
import logging

logger = logging.getLogger(__name__)

def apply_boosting_logic(vendor, purchase):
    """
    Ensures the vendor's products are boosted according to their plan's boost limit.
    Boosts or deactivates products based on current usage and allowed limits.
    """
    boost_limit = getattr(getattr(purchase, 'plan_duration', None), 'boost_product_limit', 0)

    if boost_limit == 0:
        logger.info('🚫 Boosting is not allowed for this plan.')
        return

    total_boosted = Product.objects.filter(
        user=vendor,
        payment_status="paid",
        availability_status="available",
        status="active",
        is_boosted=True
    ).count()

    logger.info('📦 Vendor boost limit: %s', boost_limit)
    logger.info('📦 Vendor total boosted products: %s', total_boosted)

    # Boost new products if under limit
    if total_boosted <= boost_limit:
        remaining_boosts = boost_limit - total_boosted
        logger.info('🚀 Remaining boosts allowed: %s', remaining_boosts)

        boosted_products = Product.objects.filter(
            user=vendor,
            payment_status="paid",
            availability_status="available",
            status="active",
            is_boosted=False
        ).order_by('-id')[:remaining_boosts]

        boosted_ids = list(boosted_products.values_list('id', flat=True))
        if boosted_ids:
            Product.objects.filter(id__in=boosted_ids).update(is_boosted=True)
            logger.info('✅ Boosted product IDs: %s', boosted_ids)

    # Deactivate excess boosted products
    elif total_boosted > boost_limit:
        extra_count = total_boosted - boost_limit
        logger.info('⚠️ Over-boosted by: %s', extra_count)

        products_to_deboost = Product.objects.filter(
            user=vendor,
            payment_status="paid",
            availability_status="available",
            status="active",
            is_boosted=True
        ).order_by('id')[:extra_count]

        unboosted_ids = list(products_to_deboost.values_list('id', flat=True))
        if unboosted_ids:
            Product.objects.filter(id__in=unboosted_ids).update(is_boosted=False)
            logger.info('🛑 Unboosted product IDs: %s', unboosted_ids)
