<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\DeleteMangaResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class DeleteMangaProvider implements ProviderInterface
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository
    ) {
    }

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

        $mangaId = $uriVariables['id'];

        try {
            $manga = $this->mangaRepository->findById($mangaId);

            if (!$manga) {
                throw new MangaNotFoundException(sprintf('Manga with id %s not found', $mangaId));
            }

            return new DeleteMangaResource($mangaId);

        } catch (MangaNotFoundException $e) {
            throw new NotFoundHttpException('Manga not found');
        }
    }
}
