<?php
declare(strict_types=1);

namespace App\State\Provider\Core;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Enum\Core\FileStatusEnum;
use App\Repository\Core\FileRepository;
use App\Service\File\Exception\FileNotFoundException;
use App\Service\File\FileManager;
use App\Service\Utils\FileUtils;
use RuntimeException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Custom provider pour récupérer l'URL d'une image
 */
final class ImageProvider implements ProviderInterface
{
    public function __construct(
        private readonly FileRepository $fileRepository,
        private readonly FileManager $fileManager,
        private readonly FileUtils $fileUtils
    ) {}

    /**
     * @param Operation $operation
     * @param array<mixed> $uriVariables
     * @param array<mixed> $context
     * @return Response|RedirectResponse
     * @throws FileNotFoundException
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response | RedirectResponse
    {
        if($operation instanceof GetCollection) {
            throw new RuntimeException('not supported', 500);
        }
        return $this->getImage($uriVariables['fileId'], $uriVariables['size']);
    }

    /**
     * @param int $fileId
     * @param string $size
     * @return Response
     * @throws FileNotFoundException
     */
    protected function getImage(int $fileId, string $size): Response {
        $file = $this->fileRepository->find($fileId);

        if (empty($file)) {
            throw new RuntimeException("Image " . $fileId . " does not exist; abort.");
        }
        if ($file->getStatus() !== FileStatusEnum::READY()->getValue()) {
            throw new RuntimeException("Image " . $fileId . " has " . $file->getStatus() . " status; abort.");
        }
        if(!$this->fileUtils->isImage($file)){
            throw new RuntimeException("File " . $fileId . " is not an image.");
        }

        $content = $this->fileManager->getImageUrl($file, $size);

        return new Response($content);
    }
}
