package pl.polskalokalnie.message;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface MessageRepository extends JpaRepository<Message, Long> {

    @Query("select m from Message m where (m.senderId = :first and m.recipientId = :second) "
            + "or (m.senderId = :second and m.recipientId = :first) order by m.createdAt asc")
    List<Message> findConversation(@Param("first") Long first, @Param("second") Long second);

    long countByRecipientIdAndSenderIdAndReadFalse(Long recipientId, Long senderId);

    @Modifying
    @Transactional
    @Query("update Message m set m.read = true where m.recipientId = :recipientId and m.senderId = :senderId and m.read = false")
    void markConversationRead(@Param("recipientId") Long recipientId, @Param("senderId") Long senderId);
}
