<?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\ChapterNotFoundException;
use App\Domain\Manga\Domain\Exception\CbzFileNotFoundException;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\DeleteCbzResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

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

        $chapterId = $uriVariables['id'];

        try {
            $chapter = $this->mangaRepository->findVisibleChapterById($chapterId);

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

            if (!$chapter->isAvailable()) {
                throw new CbzFileNotFoundException($chapterId);
            }

            return new DeleteCbzResource($chapterId);

        } catch (ChapterNotFoundException $e) {
            throw new NotFoundHttpException('Chapter not found');
        } catch (CbzFileNotFoundException $e) {
            throw new NotFoundHttpException('CBZ file not found for this chapter');
        }
    }
}
