<?php
declare(strict_types=1);

namespace App\DataPersister\Export\LicenceCmf;

use ApiPlatform\Core\DataPersister\ContextAwareDataPersisterInterface;
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 Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Security;

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

    public function supports($data, array $context = []): bool
    {
        return $data instanceof ExportRequest;
    }

    /**
     * @param $exportRequest ExportRequest Une requête d'export
     * @param array $context
     * @return File
     * @throws Exception
     * @noinspection PhpParameterNameChangedDuringInheritanceInspection
     */
    public function persist($exportRequest, array $context = []): File
    {
        /** @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()) {
            return $exporter->export($exportRequest);
        }

        // Send the export request to Messenger (@see App\Message\Handler\ExportHandler)
        $this->messageBus->dispatch(
            new Export($exportRequest)
        );
        return $file;
    }

    public function remove($data, array $context = []): void
    {
        throw new \RuntimeException('not supported', 500);
    }
}
