<?php

namespace App\Filter;

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

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

        if (null === $value ||  '' === $value || 'undefined' === $value) {
            return;
        }

        $alias = $queryBuilder->getRootAliases()[0];
        $joinAlias = $queryNameGenerator->generateJoinAlias('repositoryId');

        $queryBuilder
            ->innerJoin(sprintf('%s.repositories', $alias), $joinAlias)
            ->andWhere(sprintf('%s.id = :repositoryId', $joinAlias))
            ->setParameter('repositoryId', $value);
    }

    public function getDescription(string $resourceClass): array
    {
        return [
            'repositoryId' => [
                'property' => 'repositoryId',
                'type' => Type::BUILTIN_TYPE_INT,
                'required' => false,
                'description' => 'Filter images by repository ID.',
            ],
        ];
    }
}
