<?php
declare(strict_types=1);

namespace App\Filter\ApiPlatform\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;

/**
 * Is property included in the given CSV array
 *
 * Ex:
 *
 *    /api/accesses?id[in]=123,124,125
 */
final class InFilter 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;
        }

        if (!isset($value['in'])) {
            return;
        }

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

    /**
     * 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 . "[in]"] = [
                'property' => $property,
                'type' => Type::BUILTIN_TYPE_STRING,
                'required' => false,
                'swagger' => [
                    'description' => 'Filtre permettant d\'utiliser les IN. (usage: `id[in]=1,2,3`)',
                    'name' => 'In Filter',
                    'type' => 'Utils Filter',
                ],
            ];
        }

        return $description;
    }
}
