<?php

namespace App\Services\Geolocation;

use App\Services\Geolocation\Contracts\GeolocationResolver;
use Illuminate\Http\Client\Factory as HttpFactory;
use Illuminate\Support\Facades\Log;
use Throwable;

class IpApiGeolocationResolver implements GeolocationResolver
{
    public function __construct(
        private readonly HttpFactory $http,
        private readonly string $endpoint,
        private readonly int $timeout
    ) {
    }

    public function countryCodeForIp(string $ip): ?string
    {
        try {
            $response = $this->http
                ->timeout($this->timeout)
                ->acceptJson()
                ->get(rtrim($this->endpoint, '/') . '/' . $ip, ['fields' => 'status,countryCode']);
        } catch (Throwable $exception) {
            Log::warning('Geolocation lookup failed', [
                'ip' => $ip,
                'message' => $exception->getMessage(),
            ]);
            return null;
        }

        if (!$response->successful()) {
            return null;
        }

        $payload = $response->json();
        if (($payload['status'] ?? null) !== 'success') {
            return null;
        }

        $countryCode = $payload['countryCode'] ?? null;
        return is_string($countryCode) && $countryCode !== '' ? strtoupper($countryCode) : null;
    }
}
