<?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\CmsBundle\Twig\Extension;

use Ferienpass\CmsBundle\Controller\Page\EditionLandingController;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Routing\OfferReaderUrl;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Attribute\AsTwigFunction;

class OfferLinkExtension
{
    public function __construct(private readonly UrlGeneratorInterface $urlGenerator)
    {
    }

    /**
     * Absolute, canonical public URL for an offer's detail page
     * (/o/{edition}/{base58-uuid}-{slug}). Empty string when the offer has
     * no edition (and therefore no public landing page). Route selection
     * is centralised in EditionLandingController::offerRouteAndParams().
     */
    #[AsTwigFunction('offer_public_link')]
    public function offerPublicLink(OfferInterface $offer): string
    {
        if (!$offer->getEdition() instanceof Edition) {
            return '';
        }

        [$route, $params] = EditionLandingController::offerRouteAndParams($offer);

        return $this->urlGenerator->generate($route, $params, UrlGeneratorInterface::ABSOLUTE_URL);
    }

    /**
     * The canonical `auto_item` segment (`{base58-uuid}-{slug}`) for an offer's
     * legacy reader URL. Used by templates that still link to the Contao
     * `offer_list` reader so variants stay distinguishable; the reader 301s any
     * non-canonical form to this one.
     */
    #[AsTwigFunction('offer_auto_item')]
    public function offerAutoItem(OfferInterface $offer): string
    {
        return OfferReaderUrl::autoItem($offer);
    }
}
