package com.zhentao.repository;

import com.zhentao.entity.MatchmakerChatMessageMongo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 红娘与用户聊天消息MongoDB仓库
 */
@Repository
public interface MatchmakerChatMessageMongoRepository extends MongoRepository<MatchmakerChatMessageMongo, String> {

    /**
     * 根据消息ID查询
     */
    Optional<MatchmakerChatMessageMongo> findByMessageId(String messageId);

    /**
     * 根据会话ID查询消息（分页，按时间倒序）
     */
    Page<MatchmakerChatMessageMongo> findByConversationIdOrderBySendTimeDesc(String conversationId, Pageable pageable);

    /**
     * 根据红娘ID查询所有消息（分页）
     */
    Page<MatchmakerChatMessageMongo> findByMatchmakerIdOrderBySendTimeDesc(Long matchmakerId, Pageable pageable);

    /**
     * 根据用户ID查询所有消息（分页）
     */
    Page<MatchmakerChatMessageMongo> findByUserIdOrderBySendTimeDesc(Long userId, Pageable pageable);

    /**
     * 根据红娘ID和用户ID查询消息（分页）
     */
    Page<MatchmakerChatMessageMongo> findByMatchmakerIdAndUserIdOrderBySendTimeDesc(Long matchmakerId, Long userId, Pageable pageable);

    /**
     * 查询某时间段内的消息
     */
    @Query("{'conversation_id': ?0, 'send_time': {$gte: ?1, $lte: ?2}}")
    List<MatchmakerChatMessageMongo> findByConversationIdAndSendTimeBetween(String conversationId, Date startTime, Date endTime);

    /**
     * 统计红娘的消息数量
     */
    long countByMatchmakerIdAndSenderType(Long matchmakerId, Integer senderType);

    /**
     * 统计用户的消息数量
     */
    long countByUserIdAndSenderType(Long userId, Integer senderType);

    /**
     * 查询未读消息
     */
    List<MatchmakerChatMessageMongo> findByMatchmakerIdAndUserIdAndSenderTypeAndSendStatusLessThan(
            Long matchmakerId, Long userId, Integer senderType, Integer sendStatus);

    /**
     * 根据消息ID删除
     */
    void deleteByMessageId(String messageId);

    /**
     * 检查消息是否存在
     */
    boolean existsByMessageId(String messageId);
}
