<?php

declare(strict_types=1);

namespace App\Service\Soap\Client;

use App\Service\Soap\Api\ServiceAbstract;
use App\Service\Soap\Api\SoapClassMapper;

class ClientFactory
{
    /**
     * @param array<mixed> $options
     */
    public function __construct(
        protected string $soapUsername,
        protected string $soapPassword,
        protected string $soapHost,
        protected SoapClassMapper $classMapper,
        protected array $options = [],
    ) {
    }

    /**
     * @throws \SoapFault
     */
    public function getClientForService(ServiceAbstract $service): \SoapClient
    {
        $classmap = $this->classMapper->getClassMap();

        $options = array_merge_recursive($this->options, [
            'classmap' => $classmap,
        ]);

        return $this->initializeClient(
            $service->getWsdlPath(),
            $this->soapHost,
            $options
        );
    }

    /**
     * @param array<mixed> $options
     *
     * @throws \SoapFault
     */
    protected function initializeClient(string $wsdl, string $entrypoint, array $options = []): Client
    {
        $defaults = [
            'exceptions' => true,
            'trace' => true,
            'cache_wsdl' => WSDL_CACHE_MEMORY,
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
            'authentication' => 0,
            'login' => $this->soapUsername, // 'Datacomp',
            'password' => $this->soapPassword, // '_d@tac@#p',
            'connection_timeout' => 60,
            'soap_version' => SOAP_1_2,
            'stream_context' => stream_context_create([
                'http' => ['header' => 'Content-Type: application/soap+xml; charset=utf-8'],
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ],
            ]),
        ];

        $options = array_merge_recursive($defaults, $options);

        $result = new Client($options, $wsdl);
        $result->__setLocation($entrypoint);

        return $result;
    }
}
