<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Entity;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<DealStage> */
class DealStageRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, DealStage::class);
    }

    /**
     * @return list<DealStage>
     */
    public function findByPipelineOrdered(Pipeline $pipeline, bool $activeOnly = false): array
    {
        $qb = $this->createQueryBuilder('s')
            ->andWhere('s.pipeline = :pipeline')
            ->setParameter('pipeline', $pipeline)
            ->orderBy('s.sortOrder', 'ASC')
            ->addOrderBy('s.id', 'ASC');

        if ($activeOnly) {
            $qb->andWhere('s.isPublished = true');
        }

        return $qb->getQuery()->getResult();
    }

    public function findFirstStageForPipeline(Pipeline $pipeline): ?DealStage
    {
        return $this->createQueryBuilder('s')
            ->andWhere('s.pipeline = :pipeline')
            ->andWhere('s.isPublished = true')
            ->setParameter('pipeline', $pipeline)
            ->orderBy('s.sortOrder', 'ASC')
            ->addOrderBy('s.id', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findOneByPipelineAndSlug(Pipeline $pipeline, string $slug): ?DealStage
    {
        return $this->findOneBy(['pipeline' => $pipeline, 'slug' => $slug]);
    }

    public function getNextSortOrder(Pipeline $pipeline): int
    {
        $result = $this->createQueryBuilder('s')
            ->select('MAX(s.sortOrder)')
            ->andWhere('s.pipeline = :pipeline')
            ->setParameter('pipeline', $pipeline)
            ->getQuery()
            ->getSingleScalarResult();

        return ((int) $result) + 10;
    }
}
