<?php

declare(strict_types=1);

namespace App\Observers;

use App\Business\Inventory\InventoryRuleService;
use App\Models\DberpInventoryRule;

final class DberpInventoryRuleObserver
{
    public function __construct(
        private readonly InventoryRuleService $inventoryRuleService,
    ) {}

    public function updating(DberpInventoryRule $rule): void
    {
        if (! $rule->isDirty(['product_id', 'warehouse_id'])) {
            return;
        }

        $originalProductId = $rule->getOriginal('product_id');
        $originalWarehouseId = $rule->getOriginal('warehouse_id');

        if ($originalProductId === null || $originalWarehouseId === null) {
            return;
        }

        $this->inventoryRuleService->clearSafetyStockOnBalances((int) $originalProductId, (int) $originalWarehouseId);
    }

    public function saved(DberpInventoryRule $rule): void
    {
        $this->inventoryRuleService->syncSafetyStockToBalances($rule);
    }

    public function deleted(DberpInventoryRule $rule): void
    {
        $this->inventoryRuleService->clearSafetyStockOnBalances((int) $rule->product_id, (int) $rule->warehouse_id);
    }
}
