<?php

namespace App\Repository;

use App\Entity\Message;
use App\Entity\UserApp;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findByUser(UserApp $user): array
    {
        return $this->createQueryBuilder('m')
            ->where('m.sender = :user OR m.receiver = :user')
            ->setParameter('user', $user)
            ->orderBy('m.sendingDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findByConversation(UserApp $user1, UserApp $user2): array
    {
        return $this->createQueryBuilder('m')
            ->where('(m.sender = :user1 AND m.receiver = :user2) OR (m.sender = :user2 AND m.receiver = :user1)')
            ->setParameter('user1', $user1)
            ->setParameter('user2', $user2)
            ->orderBy('m.sendingDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findLatestMessagesByUser(UserApp $user): array
    {
        $query = $this->createQueryBuilder('m')
            ->where('m.sender = :user OR m.receiver = :user')
            ->setParameter('user', $user)
            ->orderBy('m.sendingDate', 'DESC')
            ->getQuery()
            ->getResult();

        $lastMessages = [];
        foreach ($query as $message) {
            // Identifier l'autre utilisateur dans la conversation
            $otherUser = $message->getSender() === $user ? $message->getReceiver() : $message->getSender();
            $key = $otherUser->getId();

            // Conserver uniquement le dernier message avec cet utilisateur
            if (!isset($lastMessages[$key])) {
                $lastMessages[$key] = $message;
            }
        }

        return $lastMessages;
    }


}
