<?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\Product\Repository;

use CpCreation\VitiCore\Product\Model\ProductType;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

class ProductTypeRepository extends BaseRepository
{
    private bool $defaultTypeLoaded = false;

    private ?ProductType $defaultType = null;

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

    /**
     * @return array<int, array{name: string|null}>
     */
    public function findTypes(): array
    {
        return $this->createQueryBuilder('productType')
            ->select('productType.name')
            ->groupBy('productType.name')
            ->getQuery()
            ->getArrayResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findTypeByName(string $name): ?ProductType
    {
        return $this->createQueryBuilder('p')
            ->innerJoin('p.translations', 'tr', Join::WITH, 'tr.name = :name')
            ->setParameter('name', $name)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findTypeBySlug(string $slug): ?ProductType
    {
        return $this->createQueryBuilder('p')
            ->innerJoin('p.translations', 'tr', Join::WITH, 'tr.slug = :slug')
            ->setParameter('slug', $slug)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findDefaultType(): ?ProductType
    {
        if ($this->defaultTypeLoaded) {
            return $this->defaultType;
        }

        $this->defaultTypeLoaded = true;

        return $this->defaultType = $this->createQueryBuilder('p')
            ->andWhere('p.equivalencyDefault = TRUE')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
