<?php
declare(strict_types=1);

namespace App\Filter\Person;

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

class FullNameFilter extends AbstractFilter {
    /**
     * @param string $property
     * @param mixed $value
     * @param QueryBuilder $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string $resourceClass
     * @param Operation|null $operation
     * @param mixed[] $context
     * @return void
     */
    protected function filterProperty(string $property,
                                      mixed $value,
                                      QueryBuilder $queryBuilder,
                                      QueryNameGeneratorInterface $queryNameGenerator,
                                      string $resourceClass,
                                      Operation $operation = null,
                                      array $context = []): void
    {
        if ($property !== 'fullname') {
            return;
        }
        $alias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->innerJoin(sprintf('%s.person', $alias), 'person')
            ->andWhere('person.name LIKE :search OR person.givenName LIKE :search')
            ->setParameter('search', '%'.$value.'%');
    }

    /**
     * API docs
     * @param string $resourceClass
     * @return array<string, mixed[]>
     */
    public function getDescription(string $resourceClass): array
    {
        return [
            'fullname' => [
                'property' => null,
                'type' => 'string',
                'required' => false,
                'openapi' => [
                    'description' => 'Rechercher parmi les champs name et givenName',
                ],
            ]
        ];
    }
}