<?php

/*
 * This file is part of the Serenity package.
 *
 * (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\Product\Repository;

use CpCreation\VitiCore\Product\Model\ProductTax;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Persistence\ManagerRegistry;

class ProductTaxRepository extends BaseRepository
{
    private bool $defaultTaxLoaded = false;

    private ?ProductTax $defaultTax = null;

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

    public function findOneByDefault(): ?ProductTax
    {
        if ($this->defaultTaxLoaded) {
            return $this->defaultTax;
        }

        $this->defaultTaxLoaded = true;

        $queryBuilder = $this->createQueryBuilder('t')
            ->andWhere('t.byDefault = true');

        return $this->defaultTax = $queryBuilder->getQuery()->getOneOrNullResult();
    }
}
