<?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\Entity\Core\File;
use App\Message\Command\Export;
use App\Service\ServiceIterator\ExporterIterator;
use Exception;
use RuntimeException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Bundle\SecurityBundle\Security;

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

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

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

        // 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;
    }
}
