package com.yaoyuan.jiscuss.repository;

import com.yaoyuan.jiscuss.entity.Message;
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.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface MessageRepository extends JpaRepository<Message, Integer> {

    /** Latest messages in a conversation, most recent first. */
    List<Message> findByConversationIdOrderByCreateTimeDesc(String conversationId);

    /** All messages sent by user. */
    List<Message> findBySenderIdOrderByCreateTimeDesc(Integer senderId);

    /** All messages received by user. */
    List<Message> findByReceiverIdOrderByCreateTimeDesc(Integer receiverId);

    long countByReceiverIdAndIsReadFalse(Integer receiverId);

    @Modifying
    @Transactional
    @Query("UPDATE Message m SET m.isRead = true WHERE m.conversationId = :convId AND m.receiverId = :userId")
    void markConversationReadForUser(@Param("convId") String convId, @Param("userId") Integer userId);
}
