package com.izouma.nineth.repo;

import com.izouma.nineth.domain.UserBalance;
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.util.List;
import java.util.Optional;

public interface UserBalanceRepo extends JpaRepository<UserBalance, Long>, JpaSpecificationExecutor<UserBalance> {

    List<UserBalance> findByBalanceGreaterThan(BigDecimal balance);

    List<UserBalance> findByLockedFalseAndBalanceGreaterThanOrderByUserId(BigDecimal balance);

    @Query("update UserBalance u set u.locked = false, u.lockTime = null, u.lockReason = null where u.userId = ?1")
    @Modifying
    @Transactional
    int unlock(Long userId);

    Optional<UserBalance> findByUserId(Long userId);

    @Modifying
    @Transactional
    @Query("update UserBalance b set b.balance = b.balance + ?2 where b.userId = ?1")
    void modifyBalance(Long userId, BigDecimal amount);

}
