<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\DownloadVolume;
use App\Domain\Manga\Application\QueryHandler\DownloadVolumeHandler;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Exception\VolumeNotFoundException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class DownloadVolumeProvider implements ProviderInterface
{
    public function __construct(
        private DownloadVolumeHandler $handler
    ) {
    }

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

        $query = new DownloadVolume($uriVariables['id'], (int) $uriVariables['volume']);

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