<?php

namespace App\Services;

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

class GeoIpService
{
    private static array $privateRanges = [
        '127.', '::1', '10.', '172.16.', '172.17.', '172.18.', '172.19.',
        '172.20.', '172.21.', '172.22.', '172.23.', '172.24.', '172.25.',
        '172.26.', '172.27.', '172.28.', '172.29.', '172.30.', '172.31.',
        '192.168.',
    ];

    public static function lookup(string $ip): array
    {
        foreach (self::$privateRanges as $prefix) {
            if (str_starts_with($ip, $prefix)) {
                return ['country' => null, 'country_name' => null];
            }
        }

        return Cache::remember('geoip_' . md5($ip), 86400, function () use ($ip) {
            try {
                $response = Http::timeout(3)->get(
                    "http://ip-api.com/json/{$ip}",
                    ['fields' => 'status,country,countryCode']
                );

                if ($response->successful() && $response->json('status') === 'success') {
                    return [
                        'country'      => $response->json('countryCode'),
                        'country_name' => $response->json('country'),
                    ];
                }
            } catch (\Throwable $e) {
                Log::debug('GeoIP lookup failed for ' . $ip . ': ' . $e->getMessage());
            }

            return ['country' => null, 'country_name' => null];
        });
    }
}
