<?php

declare(strict_types=1);

namespace App\Repository\Domain\MajesticTopic;

use App\Entity\Domain;
use App\Entity\Domain\MajesticTopic;
use App\Entity\Domain\TopicTrustFlow;
use App\Entity\Prospect;
use App\Service\Domain\MajesticTopicRepositoryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Query\QueryException;
use Symfony\Bridge\Doctrine\RegistryInterface;

final class DoctrineMajesticTopicRepository extends ServiceEntityRepository implements MajesticTopicRepositoryInterface
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, MajesticTopic::class);
    }

    public function findById(int $id): ?MajesticTopic
    {
        return $this->findOneBy(['id' => $id]);
    }

    /**
     * @param MajesticTopic $majesticTopic
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function save(MajesticTopic $majesticTopic): void
    {
        $this->_em->persist($majesticTopic);
        $this->_em->flush();
    }

    /**
     * @param MajesticTopic $majesticTopic
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(MajesticTopic $majesticTopic): void
    {
        $this->_em->remove($majesticTopic);
        $this->_em->flush();
    }

    public function search(string $query)
    {
        $builder = $this->createQueryBuilder('m');

        $builder
            ->join(TopicTrustFlow::class, 'ttf', 'WITH', 'ttf.topic = m.id')
            ->join(Domain::class, 'd', 'WITH', 'd.id = ttf.domain')
            ->join(Prospect::class, 'p', 'WITH', 'p.domain = d.id');

        $criteria = Criteria::create()
            ->setMaxResults(20)
            ->orderBy(['title' => 'asc'])
            ->where(Criteria::expr()->contains('title', $query));

        try {
            $query = $builder->addCriteria($criteria)->getQuery();
        } catch (QueryException $e) {
            return [];
        }

        return $query->getResult();
    }
}
