<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Manga\Application\Command\EditManga;
use App\Domain\Manga\Application\CommandHandler\EditMangaHandler;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\EditMangaResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class EditMangaProcessor implements ProcessorInterface
{
    public function __construct(
        private EditMangaHandler $handler
    ) {
    }

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

        $mangaId = $uriVariables['id'] ?? null;
        if (!$mangaId) {
            throw new \InvalidArgumentException('Manga ID is required');
        }

        $command = new EditManga(
            id: (string) $mangaId,
            title: $data->title,
            description: $data->description,
            author: $data->author,
            publicationYear: $data->publicationYear,
            genres: $data->genres,
            status: $data->status,
            rating: $data->rating,
            alternativeSlugs: $data->alternativeSlugs ?? []
        );

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