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

class OfferAnonymousReadExtension implements QueryCollectionExtensionInterface
{
    public function __construct(private readonly OfferAnonymousReadFilter $filter)
    {
    }

    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?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);
    }
}
