<?php

declare(strict_types=1);

/*
 * 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\ShippingAdditional;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @return array<int, ShippingAdditional>
     */
    public function findByQuantityAndByCountyAndByGroup(int $qty, string $county, mixed $group): array
    {
        $dateInt = (int) date('nd');

        /** @var array<int, ShippingAdditional> $result */
        $result = $this
            ->createQueryBuilder('a')
            ->innerJoin('a.groups', 'g', Join::WITH, 'g.id = :group')
            ->innerJoin('a.counties', 'counties', Join::WITH, 'counties.code = :county')
            ->andWhere('a.qtyOf < :qty')
            ->andWhere('a.qtyAt >= :qty')
            ->andWhere('a.dateOf <= :dateInt')
            ->andWhere('a.dateAt >= :dateInt')
            ->setParameter('dateInt', $dateInt)
            ->setParameter('qty', $qty)
            ->setParameter('county', $county)
            ->setParameter('group', $group)
            ->getQuery()
            ->getResult();

        return $result;
    }
}
