package de.szut.casino.coinflip;

import de.szut.casino.shared.service.BalanceService;
import de.szut.casino.user.UserEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Random;

@Service
public class CoinflipService {
    private final Random random;
    private final BalanceService balanceService;

    public CoinflipService(BalanceService balanceService, Random random) {
        this.balanceService = balanceService;
        this.random = random;
    }

    public CoinflipResult play(UserEntity user, CoinflipDto coinflipDto) {
        this.balanceService.subtractFunds(user, coinflipDto.getBetAmount());

        CoinSide coinSide = this.random.nextBoolean() ? CoinSide.HEAD : CoinSide.TAILS;
        CoinflipResult coinflipResult = new CoinflipResult(false, BigDecimal.ZERO, coinSide);
        if (coinSide == coinflipDto.getCoinSide()) {
            coinflipResult.setWin(true);

            BigDecimal payout = coinflipDto.getBetAmount().multiply(BigDecimal.TWO);
            this.balanceService.addFunds(user, payout);
            coinflipResult.setPayout(payout);
        }

        return coinflipResult;
    }
}
