<?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\Glide;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\Filesystem;
use League\Glide\Signatures\SignatureFactory;
use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;

readonly class GenerateUri
{
    public const string FM = 'avif';
    public const int QUALITY = 80;
    public const string FIT = 'cover';
    public const int WIDTH = 600;
    public const int HEIGHT = 600;

    public function __construct(private RouterInterface $router, private Filesystem $filesystem)
    {
    }

    /**
     * @param array<string, string|int|float> $parameters
     */
    public function __invoke(string $path, string $mapping, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_URL): string
    {
        $defaults = [
            'fm' => self::FM,
            'q' => self::QUALITY,
            'fit' => self::FIT,
            'w' => self::WIDTH,
            'h' => self::HEIGHT,
        ];
        $parameters = array_merge($defaults, $parameters);

        if (!$this->filesystem->exists(__DIR__.'/../../../../../../../../config/glide/private.key')) {
            throw new NoFileException('The private key private.key is missing. config/glide/private.key.');
        }

        $path = mb_ltrim($path, '/');
        $privateKey = $this->filesystem->readFile(__DIR__.'/../../../../../../../../config/glide/private.key');
        $parameters['mapping'] = $mapping;
        $parameters['s'] = SignatureFactory::create($privateKey)->generateSignature($path, $parameters);
        $parameters['path'] = $path;

        return $this->router->generate('request_image_glide', $parameters, $referenceType);
    }
}
