<?php

namespace Tests\Unit\Services\Geolocation;

use App\Services\Geolocation\CachedGeolocationResolver;
use App\Services\Geolocation\Contracts\GeolocationResolver;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Tests\TestCase;

class CachedGeolocationResolverTest extends TestCase
{
    public function testCachesHitsAndOnlyCallsInnerResolverOnce(): void
    {
        $inner = new class () implements GeolocationResolver {
            public int $calls = 0;

            public function countryCodeForIp(string $ip): ?string
            {
                $this->calls++;
                return 'GB';
            }
        };

        $resolver = new CachedGeolocationResolver($inner, new Repository(new ArrayStore()), 3600);

        $this->assertSame('GB', $resolver->countryCodeForIp('89.107.62.116'));
        $this->assertSame('GB', $resolver->countryCodeForIp('89.107.62.116'));
        $this->assertSame(1, $inner->calls);
    }

    public function testCachesMissesSoInnerResolverIsNotRetriedRepeatedly(): void
    {
        $inner = new class () implements GeolocationResolver {
            public int $calls = 0;

            public function countryCodeForIp(string $ip): ?string
            {
                $this->calls++;
                return null;
            }
        };

        $resolver = new CachedGeolocationResolver($inner, new Repository(new ArrayStore()), 3600);

        $this->assertNull($resolver->countryCodeForIp('89.107.62.116'));
        $this->assertNull($resolver->countryCodeForIp('89.107.62.116'));
        $this->assertSame(1, $inner->calls);
    }
}
