<?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\AbstractQuery;
use Doctrine\ORM\QueryBuilder;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\QueryInterface;
use Newland\Toubiz\Sync\Neos\Command\OrphanFinder;
use Newland\Toubiz\Sync\Neos\Domain\Filter\FilterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Address;
use Newland\Toubiz\Sync\Neos\Translation\TranslatableRepository;

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

    public function orphanQuery(): QueryBuilder
    {
        $query = $this->createQueryBuilder('address');

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

        $query->andWhere($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;
    }

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