<?php

namespace App\Observers;

use App\Models\BusinessProducts;
use Illuminate\Support\Facades\Cache;

class BusinessProductsObserver
{
    /**
     * Clear cache for business products
     */
    private function clearBusinessProductsCaches(BusinessProducts $product): void
    {
        // Clear cache by business_id for different limits
        if ($product->business_id) {
            // Clear different limit variations commonly used
            for ($i = 1; $i <= 50; $i++) {
                Cache::forget('business_products_limited_' . $product->business_id . '_limit_' . $i);
            }
        }
        
        // Clear general business products caches
        Cache::forget('business_products_all');
        Cache::forget('business_products_active');
        Cache::forget('business_products_popular');
    }

    /**
     * Handle the BusinessProducts "created" event.
     */
    public function created(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
    }

    /**
     * Handle the BusinessProducts "updated" event.
     */
    public function updated(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
        
        // If business_id was changed, also clear the old business cache
        if ($product->wasChanged('business_id') && $product->getOriginal('business_id')) {
            for ($i = 1; $i <= 50; $i++) {
                Cache::forget('business_products_limited_' . $product->getOriginal('business_id') . '_limit_' . $i);
            }
        }
    }

    /**
     * Handle the BusinessProducts "saved" event.
     * This covers both created and updated events
     */
    public function saved(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
    }

    /**
     * Handle the BusinessProducts "deleted" event.
     */
    public function deleted(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
    }

    /**
     * Handle the BusinessProducts "restored" event.
     */
    public function restored(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
    }

    /**
     * Handle the BusinessProducts "force deleted" event.
     */
    public function forceDeleted(BusinessProducts $product): void
    {
        $this->clearBusinessProductsCaches($product);
    }
}