<?php

declare(strict_types=1);

namespace App\Module\Integration\Infrastructure\ApiPlatform\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\Integration\Domain\Entity\ZimbraConfiguration;
use App\Module\Integration\Domain\Repository\ZimbraConfigurationRepositoryInterface;
use App\Module\Integration\Infrastructure\ApiPlatform\Resource\ZimbraSettings;
use App\Shared\Infrastructure\Service\TokenEncryptor;
use Doctrine\ORM\EntityManagerInterface;

final readonly class ZimbraSettingsProcessor implements ProcessorInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private ZimbraConfigurationRepositoryInterface $configRepository,
        private TokenEncryptor $tokenEncryptor,
    ) {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ZimbraSettings
    {
        assert($data instanceof ZimbraSettings);

        $config = $this->configRepository->findSingleton();
        if (null === $config) {
            $config = new ZimbraConfiguration();
        }

        $config->setServerUrl($data->serverUrl);
        $config->setUsername($data->username);
        $config->setCalendarPath($data->calendarPath);
        $config->setEnabled($data->enabled);

        if (null !== $data->password && '' !== $data->password) {
            $config->setEncryptedPassword($this->tokenEncryptor->encrypt($data->password));
        }

        $this->em->persist($config);
        $this->em->flush();

        $result               = new ZimbraSettings();
        $result->serverUrl    = $config->getServerUrl();
        $result->username     = $config->getUsername();
        $result->calendarPath = $config->getCalendarPath();
        $result->enabled      = $config->isEnabled();
        $result->hasPassword  = $config->hasPassword();

        return $result;
    }
}
