<?php

namespace App\Domain\Inventory\Listeners;

use App\Domain\Inventory\Enums\MovementType;
use App\Domain\Inventory\Events\PurchaseOrderReceived;
use App\Domain\Inventory\Models\Product;
use App\Domain\Inventory\Models\Warehouse;
use App\Domain\Inventory\Services\InventoryService;
use App\Domain\Shared\Services\SettingsService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class CreateReceivingMovements implements ShouldQueue
{
    public function __construct(
        private InventoryService $inventoryService,
        private SettingsService $settings,
    ) {}

    public function handle(PurchaseOrderReceived $event): void
    {
        if (!(bool) $this->settings->get('auto_receive_inventory_enabled', true)) {
            return;
        }

        try {
            $purchaseOrder = $event->purchaseOrder;
            $warehouse = $purchaseOrder->warehouse;

            if (!$warehouse) {
                Log::warning('CreateReceivingMovements: PO has no warehouse', [
                    'purchase_order_id' => $purchaseOrder->id,
                ]);
                return;
            }

            // Load items with products
            $items = $purchaseOrder->items()->with('product')->get();

            foreach ($items as $item) {
                $product = $item->product;

                if (!$product) {
                    Log::warning('CreateReceivingMovements: PO item has no product', [
                        'purchase_order_item_id' => $item->id,
                    ]);
                    continue;
                }

                // Only create movements for tracked products
                if (!$product->track_inventory) {
                    continue;
                }

                // Use quantity_received if set, otherwise quantity_ordered
                $quantity = $item->quantity_received > 0
                    ? $item->quantity_received
                    : $item->quantity_ordered;

                if ($quantity <= 0) {
                    continue;
                }

                $this->inventoryService->createMovement(
                    product: $product,
                    warehouse: $warehouse,
                    type: MovementType::PurchaseReceived,
                    quantity: $quantity,
                    actor: $event->actor,
                    unitCost: $item->unit_cost,
                    reference: $purchaseOrder,
                    reason: "استلام أمر شراء #{$purchaseOrder->order_number}",
                );
            }
        } catch (\Throwable $e) {
            Log::error('CreateReceivingMovements failed: ' . $e->getMessage(), [
                'purchase_order_id' => $event->purchaseOrder->id,
            ]);
        }
    }

    public function failed(PurchaseOrderReceived $event, \Throwable $exception): void
    {
        Log::critical('CreateReceivingMovements PERMANENTLY FAILED', [
            'purchase_order_id' => $event->purchaseOrder->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
