<?php

namespace Modules\Inventory\Observers;

use Modules\Inventory\Entities\InventoryStock;
use Modules\Inventory\Services\InventoryCacheService;

class InventoryStockObserver
{
    /**
     * Handle the InventoryStock "created" event.
     */
    public function created(InventoryStock $inventoryStock): void
    {
        // Clear stock cache when stock is created
        InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->branch_id);
    }

    /**
     * Handle the InventoryStock "updated" event.
     */
    public function updated(InventoryStock $inventoryStock): void
    {
        // Clear stock cache when stock is updated
        InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->branch_id);
        
        // Also clear if branch changed
        if ($inventoryStock->isDirty('branch_id')) {
            InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->getOriginal('branch_id'));
        }
    }

    /**
     * Handle the InventoryStock "deleted" event.
     */
    public function deleted(InventoryStock $inventoryStock): void
    {
        // Clear stock cache when stock is deleted
        InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->branch_id);
    }

    /**
     * Handle the InventoryStock "restored" event.
     */
    public function restored(InventoryStock $inventoryStock): void
    {
        // Clear stock cache when stock is restored
        InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->branch_id);
    }

    /**
     * Handle the InventoryStock "force deleted" event.
     */
    public function forceDeleted(InventoryStock $inventoryStock): void
    {
        // Clear stock cache when stock is force deleted
        InventoryCacheService::clearStockCache($inventoryStock->inventory_item_id, $inventoryStock->branch_id);
    }
}
