<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Shop\Repository;

use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\Shop\Model\ShippingCountry;
use CpCreation\VitiCore\Shop\Model\ShippingCounty;
use CpCreation\VitiCore\Shop\Model\ShippingZone;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

class ShippingZoneRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ShippingZone::class);
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findByCountryAndByCounty(ShippingCountry $country, ?ShippingCounty $county): ?ShippingZone
    {
        $qb = $this
            ->createQueryBuilder('z')
            ->innerJoin('z.countries', 'country', Join::WITH, 'country.id = :country')
            ->setParameter('country', $country->getId()->toString());

        if ($country->isCounty() && $county) {
            $qb->innerJoin('z.counties', 'county', Join::WITH, 'county.id = :county')
                ->setParameter('county', $county->getId()->toString());
        } else {
            $qb->innerJoin('z.counties', 'county', Join::WITH, 'county.id is NULL');
        }

        return $qb->getQuery()->setMaxResults(1)->getOneOrNullResult();
    }
}
