<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Newland\Toubiz\Sync\Neos\Domain\Filter\FilterInterface;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Model\Award;
use Newland\Toubiz\Sync\Neos\Translation\TranslatableRepository;

/**
 * @method Award|null findByIdentifier(string $identifier)
 * @method Award|null findOneByOriginalId(string $originalId)
 *
 * @Flow\Scope("singleton")
 */
class AwardRepository extends AbstractRepository
{
    use TranslatableRepository;

    protected $alias = 'award';

    protected function applyFilter(FilterInterface $filter, QueryBuilder $query): QueryBuilder
    {
        $this->applyBasicFilter($filter, $query);
        return $query;
    }

    public function findForDataSourceByRelatedArticleType(?int $articleType): array
    {
        $query = $this->createQueryBuilder('award')
            ->select([
                'award.originalId AS value',
                'award.name AS label'
            ])
            ->groupBy('award.originalId');

        if ($articleType !== null) {
            $query->leftJoin('award.article', 'article');
            $query->where($query->expr()->eq('article.mainType', $articleType));
        }

        return $query
            ->getQuery()
            ->execute([ ], Query::HYDRATE_ARRAY);
    }
}
