package com.honey.honey.repository;

import com.honey.honey.model.UserB;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserBRepository extends JpaRepository<UserB, Integer> {

    /**
     * Loads UserB with pessimistic write lock (SELECT ... FOR UPDATE) so that concurrent
     * withdrawals for the same user are serialized and cannot double-spend.
     */
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT b FROM UserB b WHERE b.id = :id")
    Optional<UserB> findByIdForUpdate(@Param("id") Integer id);

    @Query("SELECT COUNT(b) FROM UserB b WHERE b.depositCount > 0")
    long countUsersWithDeposit();
}


