<?php

declare(strict_types=1);

namespace App\Service\Soap;

use App\Service\Soap\Api\SoapClassMapper;
use App\Service\Soap\Api\ApiPortalPracownika;
use App\Service\Soap\Client\ClientFactory;
use Cake\Core\Configure;

/**
 * Factory for creating SOAP client instances
 *
 * Integrates with CakePHP configuration to provide SOAP client
 * using credentials from config/app.php or config/app_local.php
 */
class SoapClientFactory
{
    /**
     * Create ApiPortalPracownikaSoap instance
     *
     * @param array $config Optional custom config
     * @return ApiPortalPracownika
     * @throws \SoapFault
     */
    public static function create(array $config = [], array $options = []): ApiPortalPracownika
    {
        $classMapper = new SoapClassMapper();
        $clientFactory = new ClientFactory(
            $config['login'],
            $config['pass'],
            $config['address'],
            $classMapper,
            $options
        );

        return new ApiPortalPracownika($clientFactory, $config['address']);
    }

    /**
     * Get SOAP configuration from CakePHP config
     *
     * @return array
     */
    protected static function getConfig(): array
    {
        // Try to get from Configure first (config/app.php)
        $config = Configure::read('Datacomp');

        if (!$config) {
            // Fallback to environment or default values
            $config = [
                'login' => getenv('SOAP_LOGIN') ?: '',
                'pass' => getenv('SOAP_PASSWORD') ?: '',
                'address' => getenv('SOAP_ADDRESS') ?: '',
            ];
        }

        // Validate required config
        if (empty($config['login']) || empty($config['pass']) || empty($config['address'])) {
            throw new \RuntimeException(
                'SOAP configuration is incomplete. Required: login, pass, address'
            );
        }

        return $config;
    }
}
