<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class IpApiService
{
    /**
     * API Key for the IP API.
     *
     * @var string
     */
    private $apiKey;

    /**
     * Base URL for the IP API.
     *
     * @var string
     */
    private $baseUrl = 'https://pro.ip-api.com/json';

    /**
     * Constructor to initialize the API key from the environment file.
     */
    public function __construct()
    {
        $this->apiKey = env('IP_API_KEY', 'NCx0PDVOcBsh1pQ');
    }

    /**
     * Fetch IP-related data from the API.
     *
     * @param string $ipAddress
     * @return array|null
     */
    public function getIpDetails(string $ipAddress): ?array
    {
        $url = "{$this->baseUrl}/{$ipAddress}?key={$this->apiKey}&fields=status,country,countryCode,isp,org,as,mobile,proxy,hosting,query";

        $response = Http::get($url);

        // Check if the response is successful
        if ($response->successful()) {
            return $response->json();
        }

        // Return null in case of a failure
        return null;
    }

    /**
     * Batch lookup up to 100 IPs (ip-api pro). Returns list of result objects.
     *
     * @param  array<int, string>  $ipAddresses
     * @return array<int, array<string, mixed>>
     */
    public function batchGetIpDetails(array $ipAddresses): array
    {
        $ips = array_values(array_unique(array_filter(array_map('trim', $ipAddresses))));
        if (empty($ips)) {
            return [];
        }

        $ips = array_slice($ips, 0, 100);
        $fields = 'status,message,country,countryCode,isp,org,as,query';
        $url = "https://pro.ip-api.com/batch?key={$this->apiKey}&fields={$fields}";

        $response = Http::timeout(15)->post($url, $ips);

        if (!$response->successful()) {
            return [];
        }

        $data = $response->json();
        return is_array($data) ? $data : [];
    }
}