<?php

declare(strict_types=1);

namespace App\Doctrine;

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\Composant;
use App\Entity\Piece;
use App\Entity\Product;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\RequestStack;

use function in_array;
use function is_string;

final class SearchByNameOrReferenceExtension implements QueryCollectionExtensionInterface
{
    private const SUPPORTED_CLASSES = [
        Piece::class,
        Composant::class,
        Product::class,
    ];

    public function __construct(
        private readonly RequestStack $requestStack,
    ) {}

    public function applyToCollection(
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        ?Operation $operation = null,
        array $context = [],
    ): void {
        if (!in_array($resourceClass, self::SUPPORTED_CLASSES, true)) {
            return;
        }

        $request = $this->requestStack->getCurrentRequest();
        if (null === $request) {
            return;
        }

        $q = $request->query->get('q', '');
        if (!is_string($q) || '' === trim($q)) {
            return;
        }

        $escaped   = addcslashes(trim($q), '%_');
        $paramName = $queryNameGenerator->generateParameterName('searchQ');
        $alias     = $queryBuilder->getRootAliases()[0];

        $queryBuilder
            ->andWhere(sprintf('LOWER(%s.name) LIKE :%s OR LOWER(%s.reference) LIKE :%s', $alias, $paramName, $alias, $paramName))
            ->setParameter($paramName, '%'.strtolower($escaped).'%')
        ;
    }
}
