package com.izouma.jmrh.repo;

import com.izouma.jmrh.domain.Conversation;
import com.izouma.jmrh.domain.ResourceSupplyAndDemand;
import com.izouma.jmrh.dto.ConversationDTO;
import com.izouma.jmrh.enums.ConversationStatus;
import com.izouma.jmrh.enums.DockingRole;
import com.izouma.jmrh.enums.Exist;
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;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface ConversationRepo extends JpaRepository<Conversation, Long>, JpaSpecificationExecutor<Conversation> {
    @Transactional
    @Modifying
    @Query(value = "update conversation set status = :#{#conversationStatus.name} where id =:#{#id}", nativeQuery = true)
    Integer updateStatus(ConversationStatus conversationStatus, Long id);

    Conversation findFirstByUserIdAndToUserIdOrderByIdDesc(Long userId, Long toUserId);


    @Query("SELECT c FROM Conversation c WHERE c.sndId = :sndId AND c.userId = :userId")
    Conversation findBySndIdAAndUserId(Long sndId,Long userId);

    @Transactional
    @Modifying
    @Query("update Conversation c set c.lastUpdate = ?2, c.lastMessage = ?3 where c.sessionId = ?1")
    void updateConversation(String sessionId, LocalDateTime time, String lastMessage);

    List<Conversation> findByUserIdOrderByLastUpdateDesc(Long userId);

    @Query("select new com.izouma.jmrh.dto.ConversationDTO(c, count(m.id), o, u2) from Conversation c " +
            "left join Message m on m.sessionId = c.sessionId and m.toUserId = ?1 and m.read = false " +
            "left join OrgInfo o on c.orgId = o.id " +
            "left join User u2 on c.toUserId = u2.id " +
            "where c.userId = ?1 " +
            "group by c.id order by c.lastUpdate desc")
    List<ConversationDTO> my(Long userId);

    @Query("select new com.izouma.jmrh.dto.ConversationDTO(c, count(m.id), o, u2) from Conversation c " +
            "left join Message m on m.sessionId = c.sessionId and m.toUserId = ?1 and m.read = false " +
            "left join OrgInfo o on c.orgId = o.id " +
            "left join User u2 on c.toUserId = u2.id " +
            "where c.id = ?1 " +
            "group by c.id")
    Optional<ConversationDTO> get(Long id);
}