<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Entity;

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

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

    /**
     * @return list<DealContactAssociation>
     */
    public function findByDeal(Deal $deal): array
    {
        return $this->findBy(['deal' => $deal], ['id' => 'ASC']);
    }

    /**
     * @return list<DealContactAssociation>
     */
    public function findByContactForTimeline(int $contactId): array
    {
        return $this->createQueryBuilder('a')
            ->addSelect('d', 's')
            ->join('a.deal', 'd')
            ->leftJoin('d.stage', 's')
            ->where('a.contactId = :contactId')
            ->setParameter('contactId', $contactId)
            ->orderBy('a.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<string>
     */
    public function findDistinctLabels(): array
    {
        $rows = $this->createQueryBuilder('a')
            ->select('DISTINCT a.label AS label')
            ->andWhere('a.label IS NOT NULL')
            ->andWhere('a.label != :emptyLabel')
            ->setParameter('emptyLabel', '')
            ->orderBy('a.label', 'ASC')
            ->getQuery()
            ->getArrayResult();

        return array_values(array_map(
            static fn (array $row): string => (string) $row['label'],
            $rows
        ));
    }
}
