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

use Doctrine\ORM\QueryBuilder as DoctrineQueryBuilder;
use Ferienpass\CmsBundle\Filter\Type\FilterType;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatableInterface;

class OfferListFilter extends AbstractType
{
    /**
     * Query parameters the offer list URL carries that are not form fields of
     * their own: the two presets OfferListController::instantiateForm() expands
     * into von/bis and kostenlos/gebuehr, plus the wishlist selector.
     */
    private const EXTRA_QUERY_PARAMS = ['wann', 'preis', 'liste'];

    /** @var array<string, TranslatableInterface> */
    private array $filtersViewData = [];

    /** @param array<string,FilterType> $filterTypes */
    private array $filterTypes = [];

    public function __construct(#[AutowireIterator(FilterType::class, defaultIndexMethod: 'getName')] iterable $filterTypes)
    {
        $this->filterTypes = $filterTypes instanceof \Traversable ? iterator_to_array($filterTypes, true) : $this->filterTypes;
    }

    public function apply(DoctrineQueryBuilder $qb, FormInterface $form): void
    {
        foreach ($this->filterTypes as $k => $filter) {
            if (!is_a($filter, FilterType::class, true)) {
                continue;
            }

            $filter->apply($qb, $form->get($k));
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        foreach ($this->filterTypes as $filterName => $filterType) {
            if ($builder->has($filterName)) {
                continue;
            }

            $builder->add($filterName, $filterType::class);
        }
    }

    public function getFilterNames(): array
    {
        return array_keys($this->filterTypes);
    }

    /**
     * Every query parameter that puts the offer list into a filtered state.
     *
     * A few dozen offers expand into an unbounded URL space once categories,
     * ages, price and date presets combine, and JS-executing crawlers walk all
     * of it — each permutation a full, uncacheable list render. This is the one
     * list that decides which URLs get kept out of the index, consumed by
     * OfferListRobotsTxtListener (robots.txt) and by the pages that mount the
     * offer_list fragment (`noindex`).
     *
     * `page` is deliberately NOT part of it: offer detail pages are absent from
     * the sitemap, so the paginated list is the only path by which a crawler
     * reaches anything past the first page. Blocking it would de-index the
     * offers themselves.
     *
     * @return list<string>
     */
    public function getQueryParamNames(): array
    {
        return [...$this->getFilterNames(), ...self::EXTRA_QUERY_PARAMS];
    }

    /**
     * An empty value still counts: `?titel=` renders the same page under a
     * different URL, which is exactly what we don't want indexed.
     */
    public function isFiltered(Request $request): bool
    {
        return array_any($this->getQueryParamNames(), static fn (string $param): bool => $request->query->has($param));
    }

    /**
     * Used in the template to retrieve human-readable versions of the applied filters.
     *
     * @return array<string, TranslatableInterface>
     */
    public function humanReadable(): array
    {
        return $this->filtersViewData;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefault('csrf_protection', false);
    }

    public function getBlockPrefix(): string
    {
        return '';
    }
}
