<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Scraping\Application\Command\SetMangaPreferredSources;
use App\Domain\Scraping\Application\CommandHandler\SetMangaPreferredSourcesHandler;
use App\Domain\Scraping\Infrastructure\ApiPlatform\Resource\SetMangaPreferredSourcesResource;

final class SetMangaPreferredSourcesStateProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly SetMangaPreferredSourcesHandler $handler
    ) {
    }

    /**
     * @param SetMangaPreferredSourcesResource $data
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $mangaId = $uriVariables['id'] ?? null;

        if (!$mangaId) {
            throw new \InvalidArgumentException('Manga ID is required');
        }

        $this->handler->handle(
            new SetMangaPreferredSources(
                (string) $mangaId,
                $data->sourceIds
            )
        );

        return ['success' => true];
    }
}
