package com.izouma.jmrh.repo;

import com.izouma.jmrh.domain.Message;
import com.izouma.jmrh.dto.MessageDTO;
import com.izouma.jmrh.enums.MessageType;
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.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;

public interface MessageRepo extends JpaRepository<Message, Long>, JpaSpecificationExecutor<Message> {
    @Transactional
    @Modifying
    @Query(value = "update message set state = :#{#message.state} where id =:#{#message.id}", nativeQuery = true)
    Integer updateStatus(Message message);

    @Transactional
    @Modifying
    @Query("update Message m set m.read = true where m.sessionId = ?1 and m.toUserId = ?2")
    void readAll(String sessionId, Long toUserId);

    @Transactional
    @Modifying
    @Query("update Message m set m.read = true where m.toUserId = ?1")
    void readAll(Long toUserId);

    @Query("select new com.izouma.jmrh.dto.MessageDTO(m, p, c) from Message m " +
            "left join Post p on m.postId = p.id " +
            "left join Comment c on m.commentId = c.id " +
            "where m.sessionId = ?1 and m.type = ?2 order by m.createdAt desc")
    Page<MessageDTO> all(String sessionId, MessageType type, Pageable pageable);

    @Query("select new com.izouma.jmrh.dto.MessageDTO(m, p, c) from Message m " +
            "left join Post p on m.postId = p.id " +
            "left join Comment c on m.commentId = c.id " +
            "where m.sessionId = ?1 order by m.createdAt desc")
    Page<MessageDTO> all(String sessionId, Pageable pageable);

    long countByToUserIdAndReadFalse(Long toUserId);
}
