<?php

namespace Modules\Inventory\Observers;

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

class InventoryItemCategoryObserver
{

    public function creating(InventoryItemCategory $inventoryitemcategory)
    {
        if (branch()) {
            $inventoryitemcategory->branch_id = branch()->id;
        }
    }

    public function created(InventoryItemCategory $inventoryitemcategory): void
    {
        // Clear branch cache when category is created
        InventoryCacheService::clearBranchCache($inventoryitemcategory->branch_id);
    }

    public function updated(InventoryItemCategory $inventoryitemcategory): void
    {
        // Clear branch cache when category is updated
        InventoryCacheService::clearBranchCache($inventoryitemcategory->branch_id);
        
        // Also clear if branch changed
        if ($inventoryitemcategory->isDirty('branch_id')) {
            InventoryCacheService::clearBranchCache($inventoryitemcategory->getOriginal('branch_id'));
        }
    }

    public function deleted(InventoryItemCategory $inventoryitemcategory): void
    {
        // Clear branch cache when category is deleted
        InventoryCacheService::clearBranchCache($inventoryitemcategory->branch_id);
    }
}
