<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ZimbraBundle\Calendar\Connector\ZimbraConnector;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Zimbra\Common\Enum\AccountBy;
use Zimbra\Common\Soap\ClientFactory;
use Zimbra\Common\Struct\Header\AccountInfo;
use Zimbra\Mail\MailApi;

final readonly class SoapClientBuilder
{
    private string $username;

    private string $password;

    private string $url;

    public function __construct(private ParameterBagInterface $parameterBag, private HttpClientInterface $client)
    {
        $dsn = $this->parameterBag->get('chill_calendar.remote_calendar_dsn');
        $url = parse_url($dsn);

        $this->username = urldecode($url['user']);
        $this->password = urldecode($url['pass']);
        if ('zimbra+http' === $url['scheme']) {
            $scheme = 'http://';
            $port = $url['port'] ?? 80;
        } elseif ('zimbra+https' === $url['scheme']) {
            $scheme = 'https://';
            $port = $url['port'] ?? 443;
        } else {
            throw new \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException('Unsupported remote calendar scheme: '.$url['scheme']);
        }

        $this->url = $scheme.$url['host'].':'.$port;
    }

    private function buildApi(): MailApi
    {
        $baseClient = $this->client->withOptions([
            'base_uri' => $location = $this->url.'/service/soap',
            'verify_host' => false,
            'verify_peer' => false,
        ]);
        $psr18Client = new Psr18Client($baseClient);
        $api = new MailApi();
        $client = ClientFactory::create($location, $psr18Client);
        $api->setClient($client);

        return $api;
    }

    public function getApiForAccount(string $accountName): MailApi
    {
        $api = $this->buildApi();
        $response = $api->authByAccountName($this->username, $this->password);

        $token = $response->getAuthToken();

        $apiBy = $this->buildApi();
        $apiBy->setAuthToken($token);
        $apiBy->setTargetAccount(new AccountInfo(AccountBy::NAME, $accountName));

        return $apiBy;
    }
}
