<?php

namespace App\Support\Integration;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\PendingRequest;

final readonly class GuardedWalletApiEndpoint
{
    public function __construct(
        public string $baseUrl,
        public string $hostname,
        public int $port,
        public string $pinnedIp,
        public int $totalTimeoutSeconds,
        public int $connectTimeoutSeconds,
    ) {}

    /** @param array<string, string> $headers */
    public function request(array $headers = []): PendingRequest
    {
        $pending = Http::withHeaders($headers)
            ->withoutRedirecting()
            ->connectTimeout($this->connectTimeoutSeconds)
            ->timeout($this->totalTimeoutSeconds)
            // A proxy would resolve the hostname independently and defeat DNS pinning.
            ->withOptions(['proxy' => '']);

        if (filter_var($this->hostname, FILTER_VALIDATE_IP) === false) {
            $address = filter_var($this->pinnedIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)
                ? '['.$this->pinnedIp.']'
                : $this->pinnedIp;

            $pending->withOptions([
                'curl' => [
                    CURLOPT_RESOLVE => [$this->hostname.':'.$this->port.':'.$address],
                ],
            ]);
        }

        return $pending;
    }
}
