package com.izouma.nineth.repo;

import com.izouma.nineth.TokenHistory;
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;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public interface TokenHistoryRepo extends JpaRepository<TokenHistory, Long>, JpaSpecificationExecutor<TokenHistory> {
    List<TokenHistory> findByTokenIdOrderByCreatedAtDesc(String tokenId);

    @Query("select t from TokenHistory t where t.toUserId = ?1 or t.fromUserId = ?1 order by t.createdAt desc")
    Page<TokenHistory> userHistory(Long userId, Pageable pageable);

    @Query("select t from TokenHistory t where t.toUserId = ?2 or t.fromUserId = ?1 order by t.createdAt desc")
    Page<TokenHistory> userHistoryTo(Long userId, Long toUserId, Pageable pageable);

    @Query("select t from TokenHistory t where t.toUserId = ?1 or t.fromUserId = ?2 order by t.createdAt desc")
    Page<TokenHistory> userHistoryFrom(Long userId, Long fromUserId, Pageable pageable);

    @Query("select t from TokenHistory t where t.toUserId = ?1 or t.fromUserId = ?1 order by t.createdAt desc")
    List<TokenHistory> userHistory(Long userId);

    @Query("select t from TokenHistory t where t.toUserId in ?1 and t.price is not null")
    List<TokenHistory> userBuy(Collection<Long> userId);

    @Query("select sum(t.price) from TokenHistory t where t.toUserId = ?1 and t.price is not null")
    BigDecimal userBuy(Long userId);

    @Query("select sum(t.price) from TokenHistory t where t.fromUserId = ?1 and t.price is not null")
    BigDecimal userSale(Long userId);

    @Transactional
    @Modifying
    int deleteByTokenId(String tokenId);

    @Query("select t from TokenHistory t where t.fromUserId = t.toUserId")
    List<TokenHistory> findError();

    List<TokenHistory> findByOperationAndPriceNull(String oper);

    @Query(nativeQuery = true, value = "select to_user_id , to_user, to_avatar, sum(price) total from token_history " +
            "where created_at between ?1 and ?2 group by to_user_id order by sum(price) desc limit ?3")
    List<Map<String, Object>> sumPrice(LocalDateTime start, LocalDateTime end, int size);

    Optional<TokenHistory> findByToUserIdAndTokenId(Long toUserId, String tokenId);

    List<TokenHistory> findAllByPriceIsNotNull();

    List<TokenHistory> findByOperationAndCreatedAtBefore(String operation, LocalDateTime time);
}
