<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Manga\Application\Command\EditMultipleChapters;
use App\Domain\Manga\Application\Command\ChapterEditData;
use App\Domain\Manga\Application\CommandHandler\EditMultipleChaptersHandler;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\EditMultipleChaptersResource;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class EditMultipleChaptersProcessor implements ProcessorInterface
{
    public function __construct(
        private EditMultipleChaptersHandler $handler
    ) {
    }

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

        // Validation manuelle des données
        foreach ($data->chapters as $index => $chapterData) {
            if (!is_array($chapterData)) {
                throw new \InvalidArgumentException(sprintf('Chapter data at index %d must be an array', $index));
            }

            if (!isset($chapterData['id']) || !is_string($chapterData['id'])) {
                throw new \InvalidArgumentException(sprintf('Chapter ID at index %d must be a non-empty string', $index));
            }

            if (isset($chapterData['title']) && !is_string($chapterData['title'])) {
                throw new \InvalidArgumentException(sprintf('Chapter title at index %d must be a string', $index));
            }

            if (isset($chapterData['volume']) && !is_integer($chapterData['volume'])) {
                throw new \InvalidArgumentException(sprintf('Chapter volume at index %d must be an integer', $index));
            }
        }

        $chapters = array_map(
            fn (array $chapterData) => new ChapterEditData(
                id: $chapterData['id'],
                title: $chapterData['title'] ?? null,
                volume: $chapterData['volume'] ?? null
            ),
            $data->chapters
        );

        $command = new EditMultipleChapters($chapters);

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

        return Response::HTTP_OK;
    }
}
