<?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(PartnerProductUnassignedFilter::class)]
class PartnerProductUnassignedFilter extends AbstractFilter
{
    public const FILTER_NAME = "excludeContactId";

    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.contactPartnerProducts", 'cpp', Join::WITH, 'cpp.contact = :contact_id')
                ->andWhere('cpp.partnerProduct IS NULL')
                ->setParameter('contact_id', $value);
        }
    }

    public function getDescription(string $resourceClass): array
    {
        return [
            self::FILTER_NAME => [
                'property' => self::FILTER_NAME,
                'type' => 'boolean',
                'required' => false,
                'swagger' => [
                    'description' => 'Filter partner products that are not assigned to a given contact id',
                    'type' => 'integer', // Hier wird der Datentyp auf 'integer' gesetzt
                    'format' => 'contact_id', // Optional: Format 'partner_id' angeben, um klarzustellen, dass es sich um eine Partner-ID handelt
                ],
            ],
        ];
    }

}