<?php
declare(strict_types=1);

namespace App\Filter\Utils;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\PropertyInfo\Type;

final class FindInSetFilter 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
    {
        // otherwise filter is applied to order and page as well
        if (!$this->isPropertyEnabled($property, $resourceClass) || !$this->isPropertyMapped($property, $resourceClass)
        ) {
            return;
        }

        $alias = $queryBuilder->getRootAliases()[0];
        $parameterName = $queryNameGenerator->generateParameterName($property); // Generate a unique parameter name to avoid collisions with other filters
        $queryBuilder
            ->andWhere(sprintf('find_in_set(:%s, %s.%s) <> 0', $parameterName, $alias, $property))
            ->setParameter($parameterName, explode(',', $value));
    }

    /**
     * API docs
     * @param string $resourceClass
     * @return array<string, mixed[]>
     */
    public function getDescription(string $resourceClass): array
    {
        if (!$this->properties) {
            return [];
        }

        $description = [];
        foreach ($this->properties as $property => $strategy) {
            $description["$property"] = [
                'property' => $property,
                'type' => Type::BUILTIN_TYPE_STRING,
                'required' => false,
                'swagger' => [
                    'description' => "Filtre de type find_in_set(), vérifie que la valeur est dans le set d'un champs de type CSV",
                    'name' => 'FindInSet Filter',
                    'type' => 'Utils Filter',
                ],
            ];
        }

        return $description;
    }
}
