<?php

namespace App\Observers;

use App\Models\Order;
use App\Models\StockAdjustment;
use App\Services\StockAdjustmentService;

class OrderObserver
{
    public function updated(Order $order): void
    {
        if (!$order->wasChanged('status')) {
            return;
        }

        $oldStatus = $order->getOriginal('status');
        $newStatus = $order->status;

        // Transition TO cancelled or returned
        if (in_array($newStatus, ['cancelled', 'returned']) && !in_array($oldStatus, ['cancelled', 'returned'])) {
            // Check if already restored
            $alreadyRestored = StockAdjustment::where('order_id', $order->id)
                ->whereIn('event', ['order_cancelled', 'order_returned', 'return_received'])
                ->exists();

            if (!$alreadyRestored) {
                // Eager load items to prevent N+1 queries
                $order->loadMissing('items.variant', 'items.product');

                foreach ($order->items as $item) {
                    if ($item->product_variant_id && $item->variant) {
                        StockAdjustmentService::adjust($item->variant, $item->quantity, 'order_cancelled', [
                            'order_id' => $order->id,
                            'notes' => "Restored stock for Variant SKU {$item->product_sku} (Order #{$order->order_number} status: {$newStatus})",
                        ]);
                    }
                    if ($item->product) {
                        StockAdjustmentService::adjust($item->product, $item->quantity, 'order_cancelled', [
                            'order_id' => $order->id,
                            'notes' => "Restored stock for Product SKU {$item->product_sku} (Order #{$order->order_number} status: {$newStatus})",
                        ]);
                    }
                }
            }
        }
        
        // Transition FROM cancelled or returned back to active
        if (in_array($oldStatus, ['cancelled', 'returned']) && !in_array($newStatus, ['cancelled', 'returned'])) {
            // Eager load items
            $order->loadMissing('items.variant', 'items.product');

            foreach ($order->items as $item) {
                if ($item->product_variant_id && $item->variant) {
                    StockAdjustmentService::adjust($item->variant, -$item->quantity, 'order_placed', [
                        'order_id' => $order->id,
                        'notes' => "Re-deducted variant stock for SKU {$item->product_sku} (Order status reverted from {$oldStatus} to {$newStatus})",
                    ]);
                }
                if ($item->product) {
                    StockAdjustmentService::adjust($item->product, -$item->quantity, 'order_placed', [
                        'order_id' => $order->id,
                        'notes' => "Re-deducted product stock for SKU {$item->product_sku} (Order status reverted from {$oldStatus} to {$newStatus})",
                    ]);
                }
            }
        }
    }
}
