<?php

namespace App\Domain\Setting\Infrastructure\ApiPlatform\State\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Setting\Application\Command\ImportContentSourceCommand;
use App\Domain\Setting\Application\CommandHandler\ImportContentSourceCommandHandler;
use App\Domain\Setting\Infrastructure\ApiPlatform\Resource\ImportContentSourceResource;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use InvalidArgumentException;

readonly class ImportContentSourceStateProcessor implements ProcessorInterface
{
    public function __construct(
        private ImportContentSourceCommandHandler $handler
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): int
    {
        assert($data instanceof ImportContentSourceResource);

        try {
            $command = new ImportContentSourceCommand(
                contentSources: $data->contentSources
            );

            $this->handler->handle($command);

            return Response::HTTP_CREATED;
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
