<?php

namespace App\Repository;

use App\Entity\Document;
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<Document>
 */
class DocumentRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Document::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\Document', 'd');

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT
                id,
                stato,
                editor,
                tit_doc,
                aut_doc
            FROM document d
            JOIN rel_riferimento_documento
            ON Documento_id_doc = id
            WHERE Bibliografia_id_bib = :biblioId",
            $rsm
        );
        $query->setParameter('biblioId', $biblioId);

        return new ArrayCollection($query->getResult());
    }
}

