<?php

namespace App\Observers;

use App\Models\Order;
use App\Models\WarehouseStock;

class OrderObserver
{
    /**
     * Handle the Order "created" event.
     */
    public function created(Order $order): void
    {
        if ($order->warehouse_id) {
            WarehouseStock::adjustStock(
                $order->warehouse_id,
                $order->unit_id,
                false, // Assume sold eggs are not broken
                -$order->egg_quantity
            );
        }
    }

    /**
     * Handle the Order "updated" event.
     */
    public function updated(Order $order): void
    {
        // Revert old stock if warehouse_id, unit_id, egg_quantity, or deleted_at changed
        if ($order->isDirty(['warehouse_id', 'unit_id', 'egg_quantity'])) {
            $oldWarehouseId = $order->getOriginal('warehouse_id');
            $oldUnitId = $order->getOriginal('unit_id');
            $oldQuantity = $order->getOriginal('egg_quantity');

            if ($oldWarehouseId) {
                WarehouseStock::adjustStock($oldWarehouseId, $oldUnitId, false, $oldQuantity);
            }

            if ($order->warehouse_id) {
                WarehouseStock::adjustStock($order->warehouse_id, $order->unit_id, false, -$order->egg_quantity);
            }
        }
    }

    /**
     * Handle the Order "deleted" event.
     */
    public function deleted(Order $order): void
    {
        if (! $order->isForceDeleting() && $order->warehouse_id) {
            WarehouseStock::adjustStock($order->warehouse_id, $order->unit_id, false, $order->egg_quantity);
        }
    }

    /**
     * Handle the Order "restored" event.
     */
    public function restored(Order $order): void
    {
        if ($order->warehouse_id) {
            WarehouseStock::adjustStock($order->warehouse_id, $order->unit_id, false, -$order->egg_quantity);
        }
    }
}
