<?php

declare(strict_types=1);

namespace App\State\Processor\Organization;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResources\Organization\OrganizationCreationRequest;
use App\Entity\Access\Access;
use App\Message\Message\OrganizationCreation;
use App\Service\Organization\OrganizationFactory;
use App\Service\Utils\DatesUtils;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;

class OrganizationCreationRequestProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly MessageBusInterface $messageBus,
        private readonly OrganizationFactory $organizationFactory,
        private Security $security,
    ) {
    }

    /**
     * @param OrganizationCreationRequest $data
     * @param mixed[]                     $uriVariables
     * @param mixed[]                     $context
     *
     * @throws \Exception
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): OrganizationCreationRequest
    {
        /**
         * @var OrganizationCreationRequest $organizationCreationRequest
         */
        $organizationCreationRequest = $data;

        if (!$operation instanceof Post) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        /** @var Access|null $access */
        $access = $this->security->getUser();

        $organizationCreationRequest->setCreationDate(DatesUtils::new());
        $organizationCreationRequest->setAuthorId($access?->getId());

        if ($organizationCreationRequest->isAsync()) {
            // Send the export request to Messenger (@see App\Message\Handler\OrganizationCreationHandler)
            $this->messageBus->dispatch(
                new OrganizationCreation($organizationCreationRequest)
            );
        } else {
            // For testing purposes only
            $this->organizationFactory->create($organizationCreationRequest);
        }

        return $organizationCreationRequest;
    }
}
