<?php declare(strict_types=1);
namespace Newland\Toubiz\Events\Neos\Filter;

/*
 * This file is part of the "toubiz-events-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Doctrine\ORM\Query\Expr\Comparison;
use Doctrine\ORM\QueryBuilder;
use Neos\Neos\Domain\Model\Site;
use Neos\Flow\Annotations as Flow;

/**
 * @Flow\Scope("singleton")
 */
class EventClientFilterService
{
    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Events.Neos", path="clientFilter")
     */
    protected $configuration;

    public function addClientWhereClause(QueryBuilder $query, Site $site, string $table): void
    {
        $expression = $this->generateEqExprFor($query, $site, $table);
        if ($expression !== null) {
            $query->andWhere($expression);
        }
    }

    /**
     * @param QueryBuilder $query
     * @param Site $site
     * @param string $table
     * @return Comparison|null
     */
    public function generateEqExprFor(
        QueryBuilder $query,
        Site $site,
        string $table = null
    ): ?Comparison {
        $clientValue = $this->configuration[$site->getNodeName()] ?? null;
        if ($clientValue === null) {
            return null;
        }

        $clientField = $table ? ($table . '.client') : 'client';
        return $query->expr()->eq($clientField, $query->expr()->literal($clientValue));
    }
}
