<?php

namespace Shm\ShmBlueprints\Geo;

use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
use Shm\Shm;
use Shm\ShmUtils\ShmInit;

class ShmIPGeolocation
{
    private static ?Reader $cityDbReader = null;

    private static function mmdbPath(): string
    {
        return ShmInit::$shmDir . '/../assets/geo/GeoLite-City.mmdb';
    }

    private static function getCityDbReader(): ?Reader
    {
        if (self::$cityDbReader !== null) {
            return self::$cityDbReader;
        }

        $path = self::mmdbPath();
        if (!file_exists($path)) {
            return null;
        }

        self::$cityDbReader = new Reader($path);

        return self::$cityDbReader;
    }

    public static function getClientIp(): ?string
    {
        return $_SERVER['REMOTE_ADDR'] ?? null;
    }

    public static function getCountryIsoCode(?string $ip = null): ?string
    {
        $ip = $ip ?? self::getClientIp();
        if (!$ip) {
            return null;
        }

        $reader = self::getCityDbReader();
        if (!$reader) {
            return null;
        }

        try {
            $record = $reader->city($ip);

            return $record->country->isoCode;
        } catch (AddressNotFoundException) {
            return null;
        } catch (\Exception) {
            return null;
        }
    }

    public static function isRussia(?string $ip = null): bool
    {
        return self::getCountryIsoCode($ip) === 'RU';
    }

    public static function rpc()
    {


        return [


            'type' => Shm::structure([
                'latitude' => Shm::float(),
                'longitude' => Shm::float(),
                'ip' => Shm::string(),
            ]),
            'args' => [
                'ip' => Shm::string()
            ],
            'resolve' => function ($root, $args) {

                $currentIp = $args['ip'] ??  $_SERVER['REMOTE_ADDR'] ?? null;

                $parts = explode('.', $currentIp);
                if (count($parts) !== 4) {
                    return [
                        'ip' => $currentIp,
                    ];
                }

                if (!$currentIp) return null;



                $cityDbReader = new Reader(ShmInit::$shmDir . '/../assets/geo/GeoLite-City.mmdb');

                $record = $cityDbReader->city($currentIp);
                $latitude = $record->location->latitude;
                $longitude = $record->location->longitude;

                return [
                    'latitude' => $latitude,
                    'longitude' => $longitude,
                    'ip' => $currentIp
                ];
            }


        ];
    }
}
