<?php

namespace Modules\Inventory\Observers;

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

class InventoryMovementObserver
{

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

        if (user()) {
            $inventorymovement->added_by = user()->id;
        }
    }

    public function created(InventoryMovement $inventorymovement): void
    {
        // Clear stock cache when movement is created (affects stock levels)
        InventoryCacheService::clearStockCache($inventorymovement->inventory_item_id, $inventorymovement->branch_id);
    }

    public function updated(InventoryMovement $inventorymovement): void
    {
        // Clear stock cache when movement is updated
        InventoryCacheService::clearStockCache($inventorymovement->inventory_item_id, $inventorymovement->branch_id);
        
        // Also clear if item or branch changed
        if ($inventorymovement->isDirty('inventory_item_id')) {
            InventoryCacheService::clearStockCache($inventorymovement->getOriginal('inventory_item_id'), $inventorymovement->branch_id);
        }
        if ($inventorymovement->isDirty('branch_id')) {
            InventoryCacheService::clearStockCache($inventorymovement->inventory_item_id, $inventorymovement->getOriginal('branch_id'));
        }
    }

    public function deleted(InventoryMovement $inventorymovement): void
    {
        // Clear stock cache when movement is deleted
        InventoryCacheService::clearStockCache($inventorymovement->inventory_item_id, $inventorymovement->branch_id);
    }
}
