<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Shop\Repository;

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

class ShippingAdditionalManualRepository extends BaseRepository
{
    /**
     * @var array<string, ?ShippingAdditionalManual>
     */
    private array $quantityTypeZoneGroupCache = [];

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

    /**
     * @throws NonUniqueResultException
     */
    public function findByQuantityAndByTypeAndByZoneAndByGroup(
        int $qty,
        string $type,
        ShippingZone $zone,
        mixed $group
    ): ?ShippingAdditionalManual {
        $datetime = new \DateTime();
        $dateInt = date('nd', $datetime->getTimestamp());
        $cacheKey = implode('|', [
            $qty,
            $type,
            $zone->getId()->toString(),
            (string) $group,
            $dateInt,
        ]);

        if (\array_key_exists($cacheKey, $this->quantityTypeZoneGroupCache)) {
            return $this->quantityTypeZoneGroupCache[$cacheKey];
        }

        $qb = $this
            ->createQueryBuilder('a')
            ->addSelect('CASE WHEN a.qtyAt IS NULL THEN 1 ELSE 0 END AS HIDDEN qtyAtIsInfinite')
            ->innerJoin('a.types', 't')
            ->innerJoin('t.translations', 'tr', Join::WITH, 'tr.slug = :type')
            ->innerJoin('a.zones', 'z', Join::WITH, 'z.id = :zone')
            ->innerJoin('a.groups', 'g', Join::WITH, 'g.id = :group')
            ->andWhere('a.qtyOf < :qty')
            ->andWhere('(a.qtyAt >= :qty OR a.qtyAt IS NULL)')
            ->andWhere('a.dateOf <= :dateInt')
            ->andWhere('a.dateAt >= :dateInt')
            ->setParameter('dateInt', $dateInt)
            ->setParameter('qty', $qty)
            ->setParameter('type', $type)
            ->setParameter('group', $group)
            ->setParameter('zone', $zone->getId()->toString())
            ->addOrderBy('qtyAtIsInfinite', 'ASC')
            ->addOrderBy('a.qtyAt', 'DESC');

        return $this->quantityTypeZoneGroupCache[$cacheKey] = $qb->getQuery()->setMaxResults(1)->getOneOrNullResult();
    }

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