<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Setting\Application\Command\UpsertContentSourceCommand;
use App\Domain\Setting\Application\CommandHandler\UpsertContentSourceCommandHandler;
use App\Domain\Setting\Infrastructure\ApiPlatform\Resource\UpsertContentSourceResource;
use Symfony\Component\HttpFoundation\Response;

readonly class UpsertContentSourceStateProcessor implements ProcessorInterface
{
    public function __construct(
        private UpsertContentSourceCommandHandler $handler
    ) {
    }

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

        $id = $uriVariables['id'] ?? $data->id ?? null;

        $command = new UpsertContentSourceCommand(
            id: $id,
            baseUrl: $data->baseUrl,
            chapterUrlFormat: $data->chapterUrlFormat,
            scrapingType: $data->scrapingType,
            imageSelector: $data->imageSelector,
            nextPageSelector: $data->nextPageSelector,
            chapterSelector: $data->chapterSelector,
            testSlug: $data->testSlug,
            testChapterNumber: $data->testChapterNumber,
        );

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

        return $id ? Response::HTTP_OK : Response::HTTP_CREATED;
    }
}
