<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Controller;

use League\Glide\Filesystem\FileNotFoundException;
use League\Glide\Filesystem\FilesystemException;
use League\Glide\Responses\SymfonyResponseFactory;
use League\Glide\Signatures\SignatureException;
use League\Glide\Signatures\SignatureFactory;
use Serenity\MediaBundle\Glide\GlideServer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/cdn/{path}', name: 'request_image_glide', requirements: ['path' => '.+'])]
class ImageGlideController extends AbstractController
{
    public function __invoke(Request $request, string $path, Filesystem $filesystem, GlideServer $server): mixed
    {
        if (!$filesystem->exists(__DIR__.'/../../../../../config/glide/private.key')) {
            throw new NoFileException('The private key private.key is missing. config/glide/private.key.');
        }
        $privateKey = $filesystem->readFile(__DIR__.'/../../../../../config/glide/private.key');
        $parameters = $request->query->all();

        if (\count($parameters) > 0) {
            try {
                SignatureFactory::create($privateKey)->validateRequest($path, $parameters);
            } catch (SignatureException $e) {
                throw $this->createNotFoundException('', $e);
            }
        }

        try {
            $server->setResponseFactory(new SymfonyResponseFactory($request));
            $response = $server->getImageResponse($path, $parameters);
        } catch (\InvalidArgumentException|FileNotFoundException|FilesystemException $e) {
            throw $this->createNotFoundException('', $e);
        }

        return $response;
    }
}
