<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Twig\Extension;

use Contao\CoreBundle\Filesystem\FilesystemItem;
use Contao\CoreBundle\Image\Studio\FigureRenderer;
use Contao\FilesModel;
use Contao\Image\ImageInterface;
use Contao\Image\PictureConfiguration;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Twig\Attribute\AsTwigFunction;

class FigureExtension
{
    public function __construct(
        // The service has no class alias, so it does not autowire by type.
        #[Autowire(service: 'contao.image.studio.figure_renderer')]
        private readonly FigureRenderer $figureRenderer,
    ) {
    }

    /**
     * Renders a figure through Contao's figure component.
     *
     * Contao's own contao_figure() would do this, but it still defaults to
     * "@ContaoCore/Image/Studio/figure.html.twig", which Contao 6 deleted, so it
     * raises a LoaderError wherever it is called — and it is deprecated on top
     * of that. What it is worth keeping is the null: FigureRenderer returns null
     * for a resource it cannot build, so a missing image renders nothing instead
     * of reaching the component, which reads figure.metadata without a |default
     * and would raise on a null figure.
     *
     * Where a template needs the Figure object itself — for a caption, say — use
     * Contao's figure() and include the component directly instead.
     */
    #[AsTwigFunction('figure_html', isSafe: ['html'])]
    public function figureHtml(FilesModel|FilesystemItem|ImageInterface|int|string $from, PictureConfiguration|array|int|string|null $size, array $configuration = []): ?string
    {
        return $this->figureRenderer->render($from, $size, $configuration, '@Contao/component/_figure.html.twig');
    }
}
