<?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 ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;

/**
 * Item-level counterpart of {@see OfferAnonymousReadExtension}.
 *
 * Without this extension the `GET /api/offers/{id}` item operation would return
 * ANY offer by primary key — including DRAFT/CANCELLED offers, offers of
 * out-of-window editions and non-public ones — leaking the sensitive
 * `api:offer:anon` payload (name, description, dates, meeting point including
 * the EXACT meetingLat/meetingLng coordinates, host names and fee).
 *
 * Both operations apply the same {@see OfferAnonymousReadFilter}, so the item
 * predicate can never drift from the collection's. When it filters out the
 * requested item the Doctrine item provider yields no result and API Platform
 * returns a 404, so no data leaks.
 */
class OfferAnonymousReadItemExtension implements QueryItemExtensionInterface
{
    public function __construct(private readonly OfferAnonymousReadFilter $filter)
    {
    }

    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = []): void
    {
        if (!is_a($resourceClass, OfferInterface::class, true)) {
            return;
        }

        // Is not an anonymous user
        if (\in_array('api:offer:read', $context['groups'] ?? [], true)) {
            return;
        }

        $this->filter->apply($queryBuilder);
    }
}
