<?php

namespace App\Repository;

use App\Entity\Collector;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

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

    public function hasCreatorEditor(string $creator): bool
    {
        $em = $this->getEntityManager();
        $repo = $em->getRepository(User::class);
        
        $creator = $repo->findOneBy(['username' => $creator]);

        return in_array('ROLE_EDITOR', $creator->getRoles());
    }

    public function findAllByBibliography(int $biblioId): ?ArrayCollection
    {
        $rsm = new ResultSetMappingBuilder($this->getEntityManager());
        $rsm->addRootEntityFromClassMetadata('App\Entity\Collector', 'c');

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT
                id,
                stato,
                editor,
                nome_pers,
                luoghi_att_pers
            FROM collector c
            JOIN rel_riferimento_personaggio
            ON Personaggio_id_pers = id
            WHERE Bibliografia_id_bib = :biblioId",
            $rsm
        );
        $query->setParameter('biblioId', $biblioId);

        $collectors = new ArrayCollection($query->getResult());

        return $collectors;
    }
}
