<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Filter;

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

/**
 * @Flow\Scope("singleton")
 */
class ArticleClientFilterService
{

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Poi.Neos", path="clientFilter")
     */
    protected $configuration;

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

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

        if ($table === null) {
            /** @var From $from */
            $from = $query->getDQLPart('from')[0];
            $table = $from->getAlias();
        }

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