<?php

namespace App\Repository;

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

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

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

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT id, stato, editor, tit_coll, data_coll
            FROM collection c
            JOIN rel_riferimento_collezione
            ON Collezione_id_coll = id
            WHERE Bibliografia_id_bib = :biblioId",
            $rsm
        );
        $query->setParameter('biblioId', $biblioId);

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

        return $collections;
    }
}
