<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\ExtSoapEngine\Transport;

use Gls\GlsPoland\Soap\Engine\HttpBinding\SoapRequest;
use Gls\GlsPoland\Soap\Engine\HttpBinding\SoapResponse;
use Gls\GlsPoland\Soap\Engine\TransportInterface;
use Gls\GlsPoland\Soap\ExtSoapEngine\AbusedClient;
use Gls\GlsPoland\Soap\ExtSoapEngine\HttpBinding\LastRequestInfo;

final class TraceableTransport implements TransportInterface
{
    /**
     * @var AbusedClient
     */
    private $client;
    /**
     * @var TransportInterface
     */
    private $transport;
    /**
     * @var LastRequestInfo
     */
    private $lastRequestInfo;

    public function __construct(AbusedClient $client, TransportInterface $transport)
    {
        $this->client = $client;
        $this->transport = $transport;
        $this->lastRequestInfo = LastRequestInfo::empty();
    }

    public function request(SoapRequest $request): SoapResponse
    {
        $response = $this->transport->request($request);

        $this->lastRequestInfo = new LastRequestInfo(
            (string) $this->client->__getLastRequestHeaders(),
            $request->getRequest(),
            (string) $this->client->__getLastResponseHeaders(),
            $response->getPayload()
        );

        return $response;
    }

    public function collectLastRequestInfo(): LastRequestInfo
    {
        return $this->lastRequestInfo;
    }
}
