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

use Doctrine\DBAL\ArrayParameterType;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Enum\OfferStatus;
use Ferienpass\CoreBundle\Repository\EditionRepository;

/**
 * The single predicate that defines what an anonymous (public) API caller
 * may see: published offers belonging to an edition whose show_offers
 * window is currently open. Shared verbatim by the collection
 * ({@see OfferAnonymousReadExtension}) and item
 * ({@see OfferAnonymousReadItemExtension}) read extensions so the two can
 * never drift — a mismatch would let `GET /api/offers/{id}` leak an offer
 * the collection hides.
 *
 * Edition visibility is gated on {@see Edition::isOnline()} (the same
 * source of truth as the public /o landing pages), which returns true when
 * the edition has no show_offers task at all. Authenticated/admin
 * ("preview") callers never reach this filter — the extensions return
 * early for them.
 */
final class OfferAnonymousReadFilter
{
    public function __construct(private readonly EditionRepository $editions)
    {
    }

    public function apply(QueryBuilder $queryBuilder): void
    {
        $rootAlias = $queryBuilder->getRootAliases()[0];

        // Editions are few (one per season), so resolve "online" in PHP via
        // the entity rather than duplicating the show_offers-window logic in
        // SQL. Public API reads are cacheable, so the per-edition task load
        // only happens on a cache miss.
        $onlineEditionIds = array_values(array_filter(array_map(
            static fn (Edition $edition): ?int => $edition->getId(),
            array_filter($this->editions->findAll(), static fn (Edition $edition): bool => $edition->isOnline()),
        )));

        if ([] === $onlineEditionIds) {
            // No online edition → expose nothing (avoids an invalid `IN ()`).
            $queryBuilder->andWhere(\sprintf('%s.id = 0', $rootAlias));
        } else {
            $queryBuilder
                ->andWhere(\sprintf('%s.edition IN (:editions)', $rootAlias))
                ->setParameter('editions', $onlineEditionIds, ArrayParameterType::INTEGER)
            ;
        }

        $published = OfferStatus::PUBLISHED;
        $queryBuilder
            ->andWhere(\sprintf("JSON_CONTAINS_PATH(%s.status, 'one', '$.%s') = 1", $rootAlias, $published))
        ;

        // publish=private offers are reachable only via their private link,
        // never anonymously (mirrors the public list and the /o detail page).
        // Without this an anonymous caller could read a private offer — and,
        // since the API surfaces the UUID, derive its private-link token.
        $queryBuilder
            ->andWhere(\sprintf("%s.publish = 'public'", $rootAlias))
        ;
    }
}
