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

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

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

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

        $config->setUrl($data->url);

        if (null !== $data->tokenId && '' !== $data->tokenId
            && null !== $data->tokenSecret && '' !== $data->tokenSecret) {
            $config->setEncryptedTokenId($this->tokenEncryptor->encrypt($data->tokenId));
            $config->setEncryptedTokenSecret($this->tokenEncryptor->encrypt($data->tokenSecret));
        }

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

        $result           = new BookStackSettings();
        $result->url      = $config->getUrl();
        $result->hasToken = $config->hasToken();

        return $result;
    }
}
