<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class VeVsApi
{
    public function __construct(
        protected string $baseUrl,
        protected string $token,
        protected int $timeout = 20,
    ) {}

    /**
     * Fetch a reservation by its ref_id (e.g. RR1736197027).
     */
    public function fetchReservationByRef(string $reference): ?array
    {
        $url = rtrim($this->baseUrl, '/') . '/api/' . $this->token . '/Reservation';

        $response = Http::timeout($this->timeout)
            ->acceptJson()
            ->get($url, [
                'format' => 'json',
                'ref_id' => $reference,
            ]);

        if (! $response->ok()) {
            Log::warning('vevs.fetchReservationByRef.http_error', [
                'url'       => $url,
                'reference' => $reference,
                'status'    => $response->status(),
                'body'      => $response->body(),
            ]);

            return null;
        }

        $payload = $response->json();

        // Expect the same shape you showed earlier
        if (! is_array($payload) || ($payload['status'] ?? null) !== 'OK' || empty($payload['data'])) {
            Log::warning('vevs.fetchReservationByRef.unexpected_payload', [
                'url'       => $url,
                'reference' => $reference,
                'payload'   => $payload,
            ]);

            return null;
        }

        return $payload;
    }
}
