<?php

namespace AutoAdmin\Bundle\Content\Repository;

use AutoAdmin\Bundle\Content\Entity\AbstractContact;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use LogicException;
use ReflectionClass;
use ReflectionException;

abstract class AbstractContactRepository extends EntityRepository implements ServiceEntityRepositoryInterface
{
    /**
     * @throws ReflectionException
     * @throws Exception
     */
    public function __construct(ManagerRegistry $registry, string $entityClass)
    {
        $manager = $registry->getManagerForClass($entityClass);

        $reflection = new ReflectionClass($entityClass);

        if ($manager === null) {
            throw new LogicException(sprintf(
                'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.',
                $entityClass
            ));
        }

        if (!$reflection->isSubclassOf(AbstractContact::class)) {
            throw new LogicException(
                'Class "'.$entityClass.'" is not a sub class of AbstractContact'
            );
        }
        parent::__construct($manager, $manager->getClassMetadata($entityClass));
    }

    public function createContactQueryBuilder($alias = '_', $indexBy = null): QueryBuilder
    {
        return parent::createQueryBuilder($alias, $indexBy);
    }

    public function getSpamSender(array $fields = []): array
    {
        $queryBuilder = $this->createContactQueryBuilder('c');

        $queryBuilder
            ->addSelect(implode(', ', $fields))
            ->andWhere('c.isSpam = 1');

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