<?php

namespace App\Services\Geolocation;

use App\Services\Geolocation\Contracts\GeolocationResolver;
use Illuminate\Contracts\Cache\Repository as CacheRepository;

class CachedGeolocationResolver implements GeolocationResolver
{
    private const string CACHE_PREFIX = 'geolocation:country:';
    private const string MISS_MARKER = '__none__';

    public function __construct(
        private readonly GeolocationResolver $inner,
        private readonly CacheRepository $cache,
        private readonly int $ttlSeconds
    ) {
    }

    public function countryCodeForIp(string $ip): ?string
    {
        $cached = $this->cache->remember(
            self::CACHE_PREFIX . $ip,
            $this->ttlSeconds,
            fn () => $this->inner->countryCodeForIp($ip) ?? self::MISS_MARKER
        );

        return $cached === self::MISS_MARKER ? null : $cached;
    }
}
