<?php

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\Filesystem as AppFilesystem;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Glide\GlideServer;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Glide\GlideServerFactory;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Glide\SymfonyResponseFactory;
use League\Glide\Filesystem\FileNotFoundException;
use League\Glide\Filesystem\FilesystemException;
use League\Glide\Signatures\SignatureException;
use League\Glide\Signatures\SignatureFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
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, AppFilesystem $filesystem): mixed
    {
        $mapping = (string) $request->query->get('mapping', 'image');

        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 new AccessDeniedHttpException($e->getMessage(), $e);
            }
        }

        try {
            /** @var GlideServer $server */
            $server = GlideServerFactory::create([
                'source' => $filesystem->fs($mapping),
                'cache' => $filesystem->fs($mapping),
                'cache_with_file_extensions' => true,
                'cache_path_prefix' => 'cache',
                'driver' => 'gd',
                'max_image_size' => 9000000
            ]);
            $server->setResponseFactory(new SymfonyResponseFactory($request));
            $response = $server->getImageResponse($path, $parameters);
        } catch (FileNotFoundException $e) {
            throw $this->createNotFoundException($e->getMessage(), $e);
        } catch (\InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage(), $e);
        } catch (FilesystemException $e) {
            throw new HttpException(500, $e->getMessage(), $e);
        }

        return $response;
    }
}
