<?php
namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

/*
 * This file is part of the "toubiz-packages-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\QueryBuilder;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Filter\FilterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Filter\PackageFilter;
use Newland\Toubiz\Sync\Neos\Domain\Model\Package;

/**
 * @Flow\Scope("singleton")
 *
 * @method Package|null findByIdentifier($identifier)
 */
class PackageRepository extends AbstractRepository
{
    /**
     * @param string $originalId
     * @param string $client
     * @return Package|null
     */
    public function findOneByOriginalIdAndClient(string $originalId, string $client)
    {
        $query = $this->createQueryBuilder('package');

        $result = $query->where($query->expr()->eq('package.originalId', ':originalId'))
            ->setParameter('originalId', $originalId)
            ->andWhere($query->expr()->eq('package.client', ':client'))
            ->setParameter('client', $client)
            ->setMaxResults(1)
            ->getQuery()
            ->execute();

        return empty($result) ? null : $result[0];
    }

    /**
     * Applies filter functions (from the package filter) onto
     * the given query builder.
     *
     * @param PackageFilter $filter
     * @param QueryBuilder $query
     * @return QueryBuilder
     */
    protected function applyFilter(FilterInterface $filter, QueryBuilder $query): QueryBuilder
    {
        parent::applyBasicFilter($filter, $query);

        if ($filter->getCurrentSite()) {
            $query->andWhere($query->expr()->eq('package.client', ':client'))
                ->setParameter('client', $filter->getClient());
        }

        $identifiers = $filter->getIdentifiers();
        if (!empty($identifiers)) {
            $query->andWhere(
                $query->expr()->in('package.Persistence_Object_Identifier', $identifiers)
            );
        }

        return $query;
    }
}
