<?php

namespace App\Repository;

use App\Entity\Messages;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function getUnreadMessages(User $user): array
    {
        $query = $this->createQueryBuilder('m')
            ->andWhere('m.recipient = :recipient')
            ->andWhere('m.received IS NULL')
            ->setParameter('recipient', $user->getId()->toBinary())
            ->orderBy('m.sent', 'ASC')
            ->getQuery()
            ->getResult()
        ;

        return $query;
    }

    public function getUnreadMessageCount(User $user): int
    {
        $query = $this->createQueryBuilder('m')
            ->andWhere('m.recipient = :recipient')
            ->andWhere('m.received IS NULL')
            ->setParameter('recipient', $user->getId()->toBinary())
            ->select('COUNT(m)')
            ->getQuery()
            ->getSingleScalarResult()
        ;

        return $query;
    }

    //    /**
    //     * @return Messages[] Returns an array of Messages objects
    //     */
    //    public function findByExampleField($value): array
    //    {
    //        return $this->createQueryBuilder('m')
    //            ->andWhere('m.exampleField = :val')
    //            ->setParameter('val', $value)
    //            ->orderBy('m.id', 'ASC')
    //            ->setMaxResults(10)
    //            ->getQuery()
    //            ->getResult()
    //        ;
    //    }

    //    public function findOneBySomeField($value): ?Messages
    //    {
    //        return $this->createQueryBuilder('m')
    //            ->andWhere('m.exampleField = :val')
    //            ->setParameter('val', $value)
    //            ->getQuery()
    //            ->getOneOrNullResult()
    //        ;
    //    }
}
