<?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 SoftwareProfileSearchSoftwareFilter extends AbstractFilter
{
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
    {
        if ($property !== 'softwareProfileId') {
            return;
        }

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

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

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

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