package com.sikey.wa04.business.infrastructure.repository;

import com.sikey.wa04.business.infrastructure.dto.model.MessageRecvModel;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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 MessageRecvRepository extends JpaRepository<MessageRecvModel, Long> {
    @Transactional
    @Modifying
    @Query("update MessageRecvModel m set m.status = :status where m.id = :id")
    int updateStatusById(@Param("status") Integer status, @Param("id") Long id);

    List<MessageRecvModel> findTop120ByStatus(@NotNull Integer status);

    /**
     * 查询未读消息使用
     *
     * @param recvId        接收者Id
     * @param sendId        发送者Id
     * @param msgTypeList   消息类型数组
     *
     * @return
     */
    @Query("SELECT m FROM MessageRecvModel m WHERE m.recvId = :recvId AND m.sendId = :sendId AND m.groupId IS NULL AND  m.msgType IN :msgTypeList")
    List<MessageRecvModel> findByRecvIdAndSendIdAndMsgTypeIn(@Param("recvId") String recvId, @Param("sendId") String sendId, @Param("msgTypeList") List<Integer> msgTypeList);

    List<MessageRecvModel> findByRecvIdAndGroupIdAndSendId(@Size(max = 36) @NotNull String recvId, @Size(max = 36) String groupId, @Size(max = 36) @NotNull String sendId);
    /**
     * 查询未读群消息使用
     *
     * @param recvId        接收者Id
     * @param groupId       群Id
     * @param msgTypeList   消息类型数组
     *
     * @return
     */
    List<MessageRecvModel> findByRecvIdAndGroupIdAndMsgTypeIn(String recvId, String groupId, List<Integer> msgTypeList);


    List<MessageRecvModel> findByMsgId(@NotNull Long msgId);

    Page<MessageRecvModel> findByRecvIdAndGroupId(@Size(max = 36) @NotNull String recvId, @Size(max = 36) String groupId, Pageable pageable);

    Page<MessageRecvModel> findByRecvIdAndSendId(@Size(max = 36) @NotNull String recvId, @Size(max = 36) @NotNull String sendId, Pageable pageable);

    void deleteByRecvIdInOrSendIdIn(List<String> recvIds, List<String> sendIds);

    void deleteByRecvIdAndSendId(String recvId, String sendId);

    void deleteByRecvIdAndGroupId(String recvId, String groupId);

    @Transactional
    @Modifying
    @Query("update MessageRecvModel m set m.status = :status where m.id in :ackIdList")
    void updateStatusByIdIn(@Param("status") Integer status, @Param("ackIdList") List<Long> ackIdList);

}
