<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Entity;

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

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

    /**
     * @return list<DealField>
     */
    public function findOrdered(): array
    {
        return $this->createQueryBuilder('f')
            ->orderBy('f.sortOrder', 'ASC')
            ->addOrderBy('f.label', 'ASC')
            ->addOrderBy('f.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<DealField>
     */
    public function findActiveOrdered(): array
    {
        return $this->createQueryBuilder('f')
            ->andWhere('f.isActive = true')
            ->orderBy('f.sortOrder', 'ASC')
            ->addOrderBy('f.label', 'ASC')
            ->addOrderBy('f.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<DealField>
     */
    public function findListVisibleOrdered(): array
    {
        return $this->createQueryBuilder('f')
            ->andWhere('f.isActive = true')
            ->andWhere('f.showInList = true')
            ->orderBy('f.sortOrder', 'ASC')
            ->addOrderBy('f.label', 'ASC')
            ->addOrderBy('f.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function getNextSortOrder(): int
    {
        $sortOrder = $this->createQueryBuilder('f')
            ->select('MAX(f.sortOrder)')
            ->getQuery()
            ->getSingleScalarResult();

        return max(10, ((int) $sortOrder) + 10);
    }

    public function aliasExists(string $alias, ?int $excludedId = null): bool
    {
        $qb = $this->createQueryBuilder('f')
            ->select('COUNT(f.id)')
            ->andWhere('f.alias = :alias')
            ->setParameter('alias', $alias);

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

        return (int) $qb->getQuery()->getSingleScalarResult() > 0;
    }
}
