<?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\ShippingAuto;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @throws NonUniqueResultException
     */
    public function findByQuantityAndByCountyAndByCountry(
        int $qty,
        string $county,
        string $country,
        bool $hM = false
    ): ?ShippingAuto {
        return $this
            ->createQueryBuilder('sa')
            ->andWhere('sa.qtyOf < :qty')
            ->andWhere('(sa.qtyAt >= :qty OR sa.qtyAt IS NULL)')
            ->andWhere('sa.county = :county')
            ->andWhere('sa.country = :country')
            ->andWhere('sa.hM = :hM')
            ->setParameter('qty', $qty)
            ->setParameter('county', $county)
            ->setParameter('country', $country)
            ->setParameter('hM', $hM)
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findByQuantityAndByCountry(int $qty, string $country, bool $hM = false): ?ShippingAuto
    {
        return $this
            ->createQueryBuilder('sa')
            ->andWhere('sa.qtyOf < :qty')
            ->andWhere('(sa.qtyAt >= :qty OR sa.qtyAt IS NULL)')
            ->andWhere('sa.country = :country')
            ->andWhere('sa.hM = :hM')
            ->setParameter('qty', $qty)
            ->setParameter('country', $country)
            ->setParameter('hM', $hM)
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();
    }

    /**
     * @return list<ShippingAuto>
     */
    public function findOrder(): array
    {
        return $this
            ->createQueryBuilder('sa')
            ->addSelect('CASE WHEN sa.qtyAt IS NULL THEN 1 ELSE 0 END AS HIDDEN qtyAtIsInfinite')
            ->addOrderBy('sa.county')
            ->addOrderBy('qtyAtIsInfinite', 'ASC')
            ->addOrderBy('sa.qtyAt')
            ->getQuery()
            ->getResult();
    }
}
