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

/*
 * This file is part of the "toubiz-sync-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\RegionFilter;
use Newland\Toubiz\Sync\Neos\Domain\Model\Region;

/**
 * Region repository.
 *
 * @Flow\Scope("singleton")
 *
 * @method Region[] findAll();
 * @method Region|null findOneByOriginalId(string $originalId);
 */
class RegionRepository extends AbstractRepository
{
    /**
     * @param string[] $identifiers
     * @return Region[]
     */
    public function findByIdentifiers(array $identifiers): array
    {
        return array_map(function (string $identifier) {
            return $this->findByIdentifier($identifier);
        }, $identifiers);
    }

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

        $originalIds = $filter->getOriginalIds();
        if (!empty($originalIds)) {
            $query->andWhere(
                $query->expr()->in('region.originalId', $originalIds)
            );
        }

        return $query;
    }
}
