<?php

declare(strict_types=1);

namespace BotGuard\Helpers;

/**
 * Best-effort geo-IP resolver.
 *
 * Kept dependency-free: it prefers an edge-provided country header
 * (Cloudflare's CF-IPCountry, which is present when the site is proxied), and
 * optionally consults a MaxMind GeoLite2 database if one is configured at
 * config('geo.maxmind_db') and the reader extension is available. When neither
 * is available it returns null so "Geo Statistics" degrade gracefully rather
 * than becoming a hard dependency.
 */
final class Geo
{
    public static function country(string $ip, ?string $edgeCountry = null): ?string
    {
        // 1) Trust an edge/CDN-provided ISO country code when present.
        if ($edgeCountry !== null) {
            $code = strtoupper(trim($edgeCountry));
            if (preg_match('/^[A-Z]{2}$/', $code) && $code !== 'XX') {
                return $code;
            }
        }

        // 2) Optional MaxMind lookup (only if configured and the reader exists).
        $dbPath = (string) config('geo.maxmind_db', '');
        if ($dbPath !== '' && is_file($dbPath) && class_exists(\MaxMind\Db\Reader::class)) {
            try {
                $reader = new \MaxMind\Db\Reader($dbPath);
                $record = $reader->get($ip);
                $reader->close();
                $code = $record['country']['iso_code'] ?? null;

                return is_string($code) ? strtoupper($code) : null;
            } catch (\Throwable) {
                return null;
            }
        }

        return null;
    }
}
