<?php

namespace NoahVet\Reef\Plugin;

use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;

class ConfigureUrlPlugin implements Plugin
{
    protected string $host;

    protected string $scheme;

    protected ?int $port;

    public function __construct(string $url)
    {
        $parsedUrl = \parse_url($url);
        if (!\is_array($parsedUrl)) {
            throw new \InvalidArgumentException();
        }

        // Note : If only a hostname is passed, it ends up in "path"
        $this->host = $parsedUrl['host'] ?? $parsedUrl['path'] ?? '';
        $this->scheme = $parsedUrl['scheme'] ?? 'https';
        $this->port = $parsedUrl['port'] ?? null;
    }

    /**
     * @param callable(RequestInterface): Promise $next
     * @param callable(RequestInterface): Promise $first
     *
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    #[\Override]
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
    {
        $uri = $request->getUri()
            ->withHost($this->host)
            ->withScheme($this->scheme)
            ->withPort($this->port)
        ;

        $request = $request->withUri($uri);

        return $next($request);
    }
}
