<?php

namespace App\Observers;

use App\Models\EggCollectionItem;
use App\Models\WarehouseStock;

class EggCollectionItemObserver
{
    /**
     * Handle the EggCollectionItem "created" event.
     */
    public function created(EggCollectionItem $item): void
    {
        $item->eggCollection?->syncTotals();

        if ($warehouseId = $item->eggCollection?->warehouse_id) {
            WarehouseStock::adjustStock($warehouseId, $item->unit_id, $item->is_broken, $item->quantity);
        }
    }

    /**
     * Handle the EggCollectionItem "updated" event.
     */
    public function updated(EggCollectionItem $item): void
    {
        $item->eggCollection?->syncTotals();

        $warehouseId = $item->eggCollection?->warehouse_id;
        if (! $warehouseId) {
            return;
        }

        $oldUnitId = $item->getOriginal('unit_id');
        $oldIsBroken = $item->getOriginal('is_broken');
        $oldQuantity = $item->getOriginal('quantity');

        // Reverse old stock
        WarehouseStock::adjustStock($warehouseId, $oldUnitId, $oldIsBroken, -$oldQuantity);

        // Add new stock
        WarehouseStock::adjustStock($warehouseId, $item->unit_id, $item->is_broken, $item->quantity);
    }

    /**
     * Handle the EggCollectionItem "deleted" event.
     */
    public function deleted(EggCollectionItem $item): void
    {
        $item->eggCollection?->syncTotals();

        if ($warehouseId = $item->eggCollection?->warehouse_id) {
            WarehouseStock::adjustStock($warehouseId, $item->unit_id, $item->is_broken, -$item->quantity);
        }
    }
}
