<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\DownloadCbz;
use App\Domain\Manga\Application\QueryHandler\DownloadCbzHandler;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Manga\Domain\Exception\ChapterNotAvailableException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class DownloadCbzProvider implements ProviderInterface
{
    public function __construct(
        private DownloadCbzHandler $handler
    ) {
    }

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

        $query = new DownloadCbz($uriVariables['id']);

        try {
            $downloadResponse = $this->handler->handle($query);
            return $downloadResponse->httpResponse;
        } catch (ChapterNotAvailableException|ChapterNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
    }
}
