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

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

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

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

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

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

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

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

        return $result;
    }
}
