<?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\OrganizationDeletionRequest;
use App\Message\Message\OrganizationDeletion;
use App\Service\Organization\OrganizationFactory;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;

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

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

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

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

        return $organizationDeletionRequest;
    }
}
