<?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\ShareConfiguration;
use App\Module\Integration\Domain\Repository\ShareConfigurationRepositoryInterface;
use App\Module\Integration\Infrastructure\ApiPlatform\Resource\ShareSettings;
use App\Shared\Infrastructure\Service\TokenEncryptor;
use Doctrine\ORM\EntityManagerInterface;

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

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

        $config = $this->configRepository->findSingleton() ?? new ShareConfiguration();

        $config->setHost($data->host);
        $config->setShareName($data->shareName);
        $config->setBasePath($data->basePath);
        $config->setDomain($data->domain);
        $config->setUsername($data->username);
        $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 ShareSettings();
        $result->host        = $config->getHost();
        $result->shareName   = $config->getShareName();
        $result->basePath    = $config->getBasePath();
        $result->domain      = $config->getDomain();
        $result->username    = $config->getUsername();
        $result->enabled     = $config->isEnabled();
        $result->hasPassword = $config->hasPassword();

        return $result;
    }
}
