<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Entity;

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

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

    public function findMarkedDefaultPipeline(): ?Pipeline
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.isDefault = true')
            ->orderBy('p.id', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findDefaultPipeline(): ?Pipeline
    {
        return $this->createQueryBuilder('p')
            ->orderBy('p.isDefault', 'DESC')
            ->addOrderBy('p.id', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @return list<Pipeline>
     */
    public function findActivePipelines(): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.isPublished = true')
            ->orderBy('p.isDefault', 'DESC')
            ->addOrderBy('p.name', 'ASC')
            ->addOrderBy('p.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findFirstActivePipeline(): ?Pipeline
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.isPublished = true')
            ->orderBy('p.name', 'ASC')
            ->addOrderBy('p.id', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function countAll(): int
    {
        return (int) $this->createQueryBuilder('p')
            ->select('COUNT(p.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function clearDefaultFlag(?int $excludedId = null): void
    {
        $qb = $this->createQueryBuilder('p')
            ->update()
            ->set('p.isDefault', ':isDefault')
            ->setParameter('isDefault', false);

        if (null !== $excludedId) {
            $qb->andWhere('p.id != :excludedId')
                ->setParameter('excludedId', $excludedId);
        }

        $qb->getQuery()->execute();
    }
}
