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

use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\Shop\Model\ShopConfig;
use Doctrine\ORM\Query;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findOne(): ?ShopConfig
    {
        /** @var array{id: string}|null $configIdentifier */
        $configIdentifier = $this->createQueryBuilder('r')
            ->select('r.id')
            ->orderBy('r.createdAt', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult(Query::HYDRATE_SCALAR);

        if (null === $configIdentifier) {
            return null;
        }

        return $this->createQueryBuilder('r')
            ->addSelect('tr')
            ->leftJoin('r.translations', 'tr')
            ->andWhere('r.id = :id')
            ->setParameter('id', $configIdentifier['id'])
            ->getQuery()
            ->getOneOrNullResult();
    }
}
