<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Manga\Application\Command\RefreshMangaChapters;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Model\ValueObject\MangaId;
use Symfony\Component\Messenger\MessageBusInterface;

readonly class RefreshMangaChaptersProcessor implements ProcessorInterface
{
    public function __construct(
        private MessageBusInterface $commandBus,
        private MangaRepositoryInterface $mangaRepository
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        $mangaId = $uriVariables['mangaId'] ?? null;

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

        // Vérifier que le manga existe
        $manga = $this->mangaRepository->findById($mangaId);
        if (!$manga) {
            throw new MangaNotFoundException($mangaId);
        }

        $this->commandBus->dispatch(
            new RefreshMangaChapters(new MangaId($mangaId))
        );
    }
}
