<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\ModelGenerationConfig;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

final class ModelGenerationConfigRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ModelGenerationConfig::class);
    }

    public function findActiveForModel(): ?ModelGenerationConfig
    {
        return $this->createQueryBuilder('c')
            ->andWhere('c.active = true')
            ->orderBy('c.version', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findNextVersion(string $modelName): int
    {
        $qb = $this->createQueryBuilder('c')
            ->select('MAX(c.version)')
            ->andWhere('c.modelName = :model')
            ->setParameter('model', $modelName);

        $max = $qb->getQuery()->getSingleScalarResult();

        return $max ? ((int)$max + 1) : 1;
    }
}
