<?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 CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Liip\ImagineBundle\Imagine\Data\DataManager;
use Liip\ImagineBundle\Imagine\Filter\FilterManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

final class ImagineController
{
    public function __construct(
        private readonly FilterManager $filterManager,
        private readonly CacheManager $cacheManager,
        private readonly DataManager $dataManager,
    ) {
    }

    public function filterSvg(string $path, string $filter): RedirectResponse
    {
        $binary = $this->dataManager->find($filter, $path);

        $mimeType = $binary->getMimeType();
        $filteredBinary = ('image/svg' === $mimeType || 'image/svg+xml' === $mimeType)
            ? $binary
            : $this->filterManager->applyFilter($binary, $filter);

        $this->cacheManager->store($filteredBinary, $path, $filter);

        return new RedirectResponse(
            $this->cacheManager->resolve($path, $filter),
            Response::HTTP_MOVED_PERMANENTLY
        );
    }
}
