<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Manga\Application\Command\ToggleMangaMonitoring;
use App\Domain\Manga\Application\CommandHandler\ToggleMangaMonitoringHandler;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Model\ValueObject\MangaId;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\ToggleMonitoringResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class ToggleMonitoringProcessor implements ProcessorInterface
{
    public function __construct(
        private ToggleMangaMonitoringHandler $handler
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        if (!$data instanceof ToggleMonitoringResource) {
            throw new \InvalidArgumentException('Invalid resource type');
        }

        $mangaId = $uriVariables['mangaId'] ?? null;

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

        // La validation Symfony s'assure que enabled est un booléen valide
        if ($data->enabled === null) {
            throw new \InvalidArgumentException('Enabled field is required');
        }

        try {
            $command = new ToggleMangaMonitoring(
                new MangaId($mangaId),
                $data->enabled
            );

            $this->handler->handle($command);
        } catch (MangaNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
    }
}
