<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\DeleteChapterResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class DeleteChapterProvider implements ProviderInterface
{
    public function __construct(
        private ChapterRepositoryInterface $chapterRepository
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): DeleteChapterResource
    {
        if (!isset($uriVariables['id'])) {
            throw new NotFoundHttpException('Chapter ID is required');
        }

        $chapterId = $uriVariables['id'];

        try {
            $chapter = $this->chapterRepository->findVisibleById($chapterId);

            if (!$chapter) {
                throw new ChapterNotFoundException($chapterId);
            }

            return new DeleteChapterResource($chapterId);

        } catch (ChapterNotFoundException $e) {
            throw new NotFoundHttpException('Chapter not found');
        }
    }
}
