<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class OperatorDiscoveryService
{
    public function __construct(
        private readonly DbIpCountryOperatorService $dbIpCountryOperators
    ) {}

    /**
     * Load top ISP / operator names per country from DB-IP country pages.
     *
     * @see https://db-ip.com/country/MA
     *
     * @param  array<int, string>  $countryCodes
     * @return array{groups: array<int, array{countryCode: string, countryName: string, operators: array<int, string>}>, sources: array<string, string>}
     */
    public function discoverByCountries(array $countryCodes): array
    {
        $codes = array_values(array_unique(array_filter(array_map(
            fn ($c) => strtoupper(trim((string) $c)),
            $countryCodes
        ))));

        if (empty($codes)) {
            return ['groups' => [], 'sources' => ['db_ip' => 'none']];
        }

        sort($codes);
        $cacheKey = 'antibot:dbip:operators:' . md5(implode(',', $codes));

        $cached = Cache::get($cacheKey);
        if (is_array($cached)) {
            return $cached;
        }

        $groups = [];

        foreach ($codes as $code) {
            $result = $this->dbIpCountryOperators->fetchOperatorsForCountry($code);
            $groups[] = [
                'countryCode' => $result['countryCode'],
                'countryName' => $result['countryName'],
                'operators' => $result['operators'],
            ];

            if (count($codes) > 1) {
                usleep(350000);
            }
        }

        $payload = [
            'groups' => $groups,
            'sources' => [
                'db_ip' => 'https://db-ip.com/country/',
            ],
        ];

        Cache::put($cacheKey, $payload, now()->addDays(7));

        return $payload;
    }
}
