<?php

namespace App\Support\Integration;

use App\Contracts\WalletApiDnsResolver;

final readonly class WalletApiRequestGuard
{
    private const MAX_CONNECT_TIMEOUT_SECONDS = 5;

    public function __construct(
        private WalletApiDnsResolver $dnsResolver,
    ) {}

    public function guard(?string $rawBaseUrl, int $timeoutSeconds): ?GuardedWalletApiEndpoint
    {
        $baseUrl = WalletApiUrlSanitizer::normalizeAndValidate($rawBaseUrl);
        if ($baseUrl === null) {
            return null;
        }

        $parts = parse_url($baseUrl);
        if (! is_array($parts) || ! is_string($parts['host'] ?? null)) {
            return null;
        }

        $hostname = trim((string) $parts['host'], '[]');
        $port = isset($parts['port']) ? (int) $parts['port'] : 443;

        if (filter_var($hostname, FILTER_VALIDATE_IP) !== false) {
            $addresses = [$hostname];
        } else {
            // Pinning is required for hostnames; without cURL, a second DNS lookup could rebind.
            if (! extension_loaded('curl')
                || ! defined('CURLOPT_RESOLVE')
                || (! function_exists('curl_exec') && ! function_exists('curl_multi_exec'))
            ) {
                return null;
            }

            try {
                $addresses = $this->dnsResolver->resolveAll($hostname);
            } catch (\Throwable) {
                return null;
            }
        }

        $addresses = array_values(array_unique(array_filter(
            $addresses,
            static fn (mixed $address): bool => is_string($address) && $address !== '',
        )));

        if ($addresses === []) {
            return null;
        }

        foreach ($addresses as $address) {
            if (! WalletApiUrlSanitizer::isPublicIp($address)) {
                return null;
            }
        }

        $totalTimeoutSeconds = max(1, $timeoutSeconds);

        return new GuardedWalletApiEndpoint(
            baseUrl: $baseUrl,
            hostname: $hostname,
            port: $port,
            pinnedIp: $addresses[0],
            totalTimeoutSeconds: $totalTimeoutSeconds,
            connectTimeoutSeconds: min(self::MAX_CONNECT_TIMEOUT_SECONDS, $totalTimeoutSeconds),
        );
    }
}
