<?php
namespace App\Filter;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\ApiFilter;
use Doctrine\ORM\QueryBuilder;
use ApiPlatform\Metadata\Operation;

#[ApiFilter(UserTripEventFilter::class)]
class UserTripEventFilter extends AbstractFilter
{
    protected function filterProperty(
        string $property,
        mixed $value,
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        ?Operation $operation = null,
        array $context = []
    ): void {
        if ($property !== 'tripId') {
            return;
        }

        $rootAlias = $queryBuilder->getRootAliases()[0];
        $parameterName = $queryNameGenerator->generateParameterName('tripId');

        $queryBuilder
            ->join("$rootAlias.userTrip", "userTrip")
            ->join("userTrip.trip", "trip")
            ->andWhere("trip.id = :$parameterName")
            ->setParameter($parameterName, $value);
    }

    public function getDescription(string $resourceClass): array
    {
        return [
            'tripId' => [
                'property' => 'tripId',
                'type' => 'int',
                'required' => false,
                'description' => 'Filter UserTripEvents by Trip ID',
            ],
        ];
    }
}
