<?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\Address;

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

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

        $query->leftJoin('address.articles', 'articles')
            ->leftJoin('address.articlesAsMainAddress', 'articlesAsMainAddress')
            ->leftJoin('address.eventsAsLocation', 'eventsAsLocation')
            ->leftJoin('address.eventsAsOrganizer', 'eventsAsOrganizer');

        $query->where($query->expr()->andX(
            $query->expr()->isNull('articles.Persistence_Object_Identifier'),
            $query->expr()->isNull('articlesAsMainAddress.Persistence_Object_Identifier'),
            $query->expr()->isNull('eventsAsLocation.Persistence_Object_Identifier'),
            $query->expr()->isNull('eventsAsOrganizer.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;
    }
}
