package de.szut.casino.lootboxes;

import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class LootBoxService {
    private final UserRepository userRepository;

    public LootBoxService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public boolean hasSufficientBalance(UserEntity user, BigDecimal price) {
        return user.getBalance().compareTo(price) < 0;
    }

    public RewardEntity determineReward(LootBoxEntity lootBox) {
        double randomValue = Math.random();
        BigDecimal cumulativeProbability = BigDecimal.ZERO;

        for (RewardEntity reward : lootBox.getRewards()) {
            cumulativeProbability = cumulativeProbability.add(reward.getProbability());
            if (randomValue <= cumulativeProbability.doubleValue()) {
                return reward;
            }
        }

        return lootBox.getRewards().getLast();
    }

    public void handleBalance(UserEntity user, LootBoxEntity lootBox, RewardEntity reward) {
        user.setBalance(user.getBalance().subtract(lootBox.getPrice()));
        user.setBalance(user.getBalance().add(reward.getValue()));
        userRepository.save(user);
    }
}
