<?php

declare(strict_types=1);

namespace App\State\Processor\Export\LicenceCmf;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResources\Export\ExportRequest;
use App\Entity\Access\Access;
use App\Message\Message\Export;
use App\Service\Network\Utils as NetworkUtils;
use App\Service\ServiceIterator\ExporterIterator;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;

class ExportRequestProcessor implements ProcessorInterface
{
    public function __construct(
        private Security $security,
        private MessageBusInterface $messageBus,
        private ExporterIterator $handler,
        private NetworkUtils $networkUtils,
    ) {
    }

    /**
     * @param ExportRequest $exportRequest
     * @param mixed[]       $uriVariables
     * @param mixed[]       $context
     *
     * @throws \Exception
     */
    public function process(mixed $exportRequest, Operation $operation, array $uriVariables = [], array $context = []): ExportRequest
    {
        if ($operation instanceof Delete) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        /** @var Access $access */
        $access = $this->security->getUser();
        $exportRequest->setRequesterId($access->getId());

        if (!$this->networkUtils->isCMFAndActiveNow($access->getOrganization())) {
            throw new \RuntimeException('This organization is not a member of the CMF', Response::HTTP_FORBIDDEN);
        }

        // Prepare the file record and attach its id to the export request
        $exporter = $this->handler->getExporterFor($exportRequest);
        $file = $exporter->prepareFile($exportRequest, true);

        $exportRequest->setFileId($file->getId());

        if (!$exportRequest->isAsync()) {
            $exporter->export($exportRequest);
        } else {
            // Send the export request to Messenger (@see App\Message\Handler\ExportHandler)
            $this->messageBus->dispatch(
                new Export($exportRequest)
            );
        }

        return $exportRequest;
    }
}
