<?php

namespace Tests\Unit\Services\Geolocation;

use App\Services\Geolocation\IpApiGeolocationResolver;
use Illuminate\Http\Client\Factory as HttpFactory;
use Illuminate\Http\Client\Request as HttpRequest;
use Tests\TestCase;

class IpApiGeolocationResolverTest extends TestCase
{
    public function testReturnsCountryCodeOnSuccessfulLookup(): void
    {
        $http = new HttpFactory();
        $http->fake([
            'http://ip-api.com/json/89.107.62.116*' => $http->response([
                'status' => 'success',
                'countryCode' => 'GB',
            ]),
        ]);

        $resolver = new IpApiGeolocationResolver($http, 'http://ip-api.com/json', 2);

        $this->assertSame('GB', $resolver->countryCodeForIp('89.107.62.116'));

        $http->assertSent(fn (HttpRequest $request) => str_contains($request->url(), 'fields=status%2CcountryCode'));
    }

    public function testReturnsNullWhenProviderMarksLookupAsFailed(): void
    {
        $http = new HttpFactory();
        $http->fake([
            '*' => $http->response(['status' => 'fail', 'message' => 'private range']),
        ]);

        $resolver = new IpApiGeolocationResolver($http, 'http://ip-api.com/json', 2);

        $this->assertNull($resolver->countryCodeForIp('10.0.0.1'));
    }

    public function testReturnsNullOnTransportError(): void
    {
        $http = new HttpFactory();
        $http->fake(fn () => throw new \RuntimeException('connection refused'));

        $resolver = new IpApiGeolocationResolver($http, 'http://ip-api.com/json', 2);

        $this->assertNull($resolver->countryCodeForIp('89.107.62.116'));
    }
}
