<?php

namespace App\Domain\Inventory\Listeners;

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

class DeductKitComponents implements ShouldQueue
{
    public function __construct(
        private InventoryService $inventoryService,
    ) {}

    public function handle(KitAssembled $event): void
    {
        try {
            $kit = $event->kit;
            $assemblyQuantity = $event->quantity;

            // Load kit components with products
            $components = $kit->components()->with('product')->get();

            if ($components->isEmpty()) {
                Log::warning('DeductKitComponents: Kit has no components', [
                    'kit_id' => $kit->id,
                ]);
                return;
            }

            // Determine warehouse — use the first product's primary warehouse
            // or the academy's default warehouse
            $warehouse = $this->resolveWarehouse($kit);

            if (!$warehouse) {
                Log::error('DeductKitComponents: Cannot determine warehouse for kit', [
                    'kit_id' => $kit->id,
                ]);
                return;
            }

            foreach ($components as $component) {
                $product = $component->product;

                if (!$product || !$product->track_inventory) {
                    continue;
                }

                // Total quantity to deduct = component quantity * assembly quantity
                $totalQuantity = $component->quantity * $assemblyQuantity;

                $this->inventoryService->createMovement(
                    product: $product,
                    warehouse: $warehouse,
                    type: MovementType::KitAssembly,
                    quantity: $totalQuantity,
                    actor: $event->actor,
                    reference: $kit,
                    reason: "تجميع طقم: {$kit->name_ar} × {$assemblyQuantity}",
                );
            }
        } catch (\Throwable $e) {
            Log::error('DeductKitComponents failed: ' . $e->getMessage(), [
                'kit_id' => $event->kit->id,
                'quantity' => $event->quantity,
            ]);
        }
    }

    private function resolveWarehouse($kit): ?Warehouse
    {
        // Try to find the default/primary warehouse for this academy
        return Warehouse::where('academy_id', $kit->academy_id)
            ->where('is_active', true)
            ->orderBy('id')
            ->first();
    }

    public function failed(KitAssembled $event, \Throwable $exception): void
    {
        Log::critical('DeductKitComponents PERMANENTLY FAILED', [
            'kit_id' => $event->kit->id,
            'quantity' => $event->quantity,
            'error' => $exception->getMessage(),
        ]);
    }
}
