<?php

namespace App\Patient\Repository;

use App\Patient\Entity\PatientNote;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class PatientNoteRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, PatientNote::class);
    }

    public function findByUuid(string $uuid): ?PatientNote
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /**
     * Notes for a record, pinned first then newest first.
     *
     * @return PatientNote[]
     */
    public function findByRecord(PatientRecord $record): array
    {
        return $this->createQueryBuilder('n')
            ->where('n.record = :record')
            ->setParameter('record', $record)
            ->orderBy('n.pinned', 'DESC')
            ->addOrderBy('n.id', 'DESC')
            ->getQuery()
            ->getResult();
    }

    public function save(PatientNote $n): void
    {
        $this->getEntityManager()->persist($n);
        $this->getEntityManager()->flush();
    }

    public function remove(PatientNote $n): void
    {
        $this->getEntityManager()->remove($n);
        $this->getEntityManager()->flush();
    }
}
