<?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\Command\OrphanFinder;
use Newland\Toubiz\Sync\Neos\Domain\Filter\FilterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Medium;

/**
 * Medium repository.
 *
 * @Flow\Scope("singleton")
 *
 * @method Medium|null findOneByOriginalId(string $originalId)
 */
class MediumRepository extends AbstractRepository implements OrphanFinder
{

    /**
     * @return iterable
     */
    public function findOrphans()
    {
        $query = $this->createQueryBuilder('medium');

        $query->leftJoin('medium.events', 'events')
            ->leftJoin('medium.articles', 'articles')
            ->leftJoin('medium.packages', 'packages');

        $query->where($query->expr()->andX(
            $query->expr()->isNull('events.Persistence_Object_Identifier'),
            $query->expr()->isNull('articles.Persistence_Object_Identifier'),
            $query->expr()->isNull('packages.Persistence_Object_Identifier')
        ));

        return $query->getQuery()->execute();
    }


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