<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\Client\Soap;

use Gls\GlsPoland\Soap\Client\Soap\Metadata\MetadataFactory;
use Gls\GlsPoland\Soap\Engine\Engine;
use Gls\GlsPoland\Soap\Engine\EngineInterface;
use Gls\GlsPoland\Soap\Engine\LazyEngine;
use Gls\GlsPoland\Soap\Engine\TransportInterface;
use Gls\GlsPoland\Soap\ExtSoapEngine\AbusedClient;
use Gls\GlsPoland\Soap\ExtSoapEngine\ExtSoapDriver;
use Gls\GlsPoland\Soap\ExtSoapEngine\ExtSoapMetadata;
use Gls\GlsPoland\Soap\ExtSoapEngine\ExtSoapOptions;
use Gls\GlsPoland\Soap\ExtSoapEngine\Transport\ExtSoapClientTransport;

final class DefaultEngineFactory
{
    public static function create(ExtSoapOptions $options, ?TransportInterface $transport = null): EngineInterface
    {
        return new LazyEngine(static function () use ($options, $transport) {
            $client = AbusedClient::createFromOptions($options);
            $transport = $transport ?? new ExtSoapClientTransport($client);
            $driver = ExtSoapDriver::createFromClient(
                $client,
                MetadataFactory::lazy(new ExtSoapMetadata($client))
            );

            return new Engine($driver, $transport);
        });
    }
}
