<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 10.06.24
 */


namespace App\Filter;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ApiPlatform\Metadata\ApiFilter;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;

#[ApiFilter(ProductUnassignedFilter::class)]
class ProductUnassignedFilter extends AbstractFilter
{
    public const FILTER_NAME = "excludePartnerId";

    public function __construct(ManagerRegistry $managerRegistry, ?LoggerInterface $logger = null, ?array $properties = null)
    {
        parent::__construct($managerRegistry, $logger, $properties);
    }

    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?\ApiPlatform\Metadata\Operation $operation = null, array $context = []): void
    {
        if ($property !== self::FILTER_NAME) {
            return;
        }

        if ($value) {
            // Alias für das Produkt
            $rootAlias = $queryBuilder->getRootAliases()[0];

            // Join mit PartnerProduct
            $queryBuilder->leftJoin("$rootAlias.partnerProducts", 'pp', Join::WITH, 'pp.partner = :partner_id')
                ->andWhere('pp.product IS NULL')
                ->setParameter('partner_id', $value);
        }
    }

    public function getDescription(string $resourceClass): array
    {
        return [
            self::FILTER_NAME => [
                'property' => self::FILTER_NAME,
                'type' => 'boolean',
                'required' => false,
                'swagger' => [
                    'description' => 'Filter products that are not assigned to a given partner id',
                    'type' => 'integer',
                    'format' => 'partner_id',
                ],
            ],
        ];
    }

}