<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\JobImportService;
use App\Services\VevsClientFactory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ImportVevsReservationCommand extends Command
{
    protected $signature = 'vevs:import-reservation
                            {reference : VEVS booking reference}
                            {--brand=jimny : Brand key (jimny|dreamdrives)}';

    protected $description = 'Import a reservation from VEVS and create/update a Job';

    public function handle(
        VevsClientFactory $vevsFactory,
        JobImportService  $jobImportService,
    ): int {
        $ref      = (string) $this->argument('reference');
        $brandKey = (string) $this->option('brand');

        $client   = $vevsFactory->forBrandKey($brandKey);
        $payload  = $client->fetchReservationByRef($ref);

        if ($payload === null) {
            $this->error("No reservation found in VEVS for [{$ref}] on [{$brandKey}] (null payload)");
            return self::FAILURE;
        }

        // Dream Drives payload shape:
        // { "status": "OK", "code": "200", "data": { ...booking... } }
        $booking = $payload['data'] ?? $payload;

        // If the payload is a flat list (["OK","200"]), it's not a booking.
        if (is_array($booking) && array_is_list($booking)) {
            Log::warning('VEVS import returned non-booking payload (list)', [
                'brand'   => $brandKey,
                'ref'     => $ref,
                'payload' => $payload,
            ]);

            $this->error("VEVS returned a non-booking payload for [{$ref}] on [{$brandKey}]");
            $this->line('Raw payload: ' . json_encode($payload));

            return self::FAILURE;
        }

        // Sanity-check we have something that looks like a booking.
        if (
            ! isset($booking['ref_id']) &&
            ! isset($booking['booking_id']) &&
            ! isset($booking['uuid']) &&
            ! isset($booking['id'])
        ) {
            Log::warning('VEVS import returned unexpected booking payload shape', [
                'brand'   => $brandKey,
                'ref'     => $ref,
                'payload' => $payload,
            ]);

            $this->error("VEVS returned an unexpected booking payload shape for [{$ref}] on [{$brandKey}]");
            $this->line('Raw payload: ' . json_encode($payload));

            return self::FAILURE;
        }

        // At this point we believe we have a real booking payload – hand off to the importer.
        $job = $jobImportService->importFromVevsPayload($booking, $brandKey);

        $this->info("Imported/updated Job #{$job->id} ({$brandKey}) for VEVS ref {$ref}");

        return self::SUCCESS;
    }
}
