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

namespace CpCreation\VitiCore\Shop\Repository;

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

class ShopConfigMultipleRepository extends BaseRepository
{
    /**
     * @var array<string, ?ShopConfigMultiple>
     */
    private array $quantityTypeZoneCache = [];

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

    /**
     * @throws NonUniqueResultException
     */
    public function findByQuantityAndByTypeAndByZone(int $qty, string $type, ShippingZone $zone): ?ShopConfigMultiple
    {
        $cacheKey = implode('|', [
            $qty,
            $type,
            $zone->getId()->toString(),
        ]);

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

        return $this->quantityTypeZoneCache[$cacheKey] = $this
            ->createQueryBuilder('p')
            ->innerJoin('p.types', 't')
            ->innerJoin('t.translations', 'tr', Join::WITH, 'tr.slug = :type')
            ->innerJoin('p.zones', 'z', Join::WITH, 'z.id = :zone')
            ->andWhere('p.qtyOf < :qty')
            ->andWhere('p.qtyAt >= :qty')
            ->setParameter('qty', $qty)
            ->setParameter('type', $type)
            ->setParameter('zone', $zone->getId()->toString())
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
