import BackendError from '../../errors/BackendError';
import Locator from '../../services/Locator';
import CasinoRoundsMode from './CasinoRoundsMode';

/**
 * A casino rounds mode where the player's win is credited to the balance
 * immediately after each spin (unless it's a subgame like freespins or respins).
 *
 * Inherits most logic from {@link CasinoRoundsMode}, but overrides:
 * - Balance is updated *per spin* (transactional behavior).
 * - `startRound` subtracts in-game balance cost.
 *
 * Used for promotional modes with real-time balance adjustments.
 */
export default class TransCasinoRoundsMode extends CasinoRoundsMode
{
    constructor(betConfig, gameData, lines)
    {
        super(betConfig, gameData, lines);
        this._name = 'transactionalCasinoRounds';
    }


    /**
     * Overrides translatedTotalWin to return 0.
     *
     * In transactional mode, win is already credited to the balance after each spin,
     * so there's no need to pass it to the previous mode upon exit.
     *
     * @returns {number} Always returns 0.
     */
    get translatedTotalWin() {
        return 0;
    }

    /**
     * Overrides balance update logic: subtracts game balance immediately
     * @param {BalanceModel} balanceModel
     */
    async startRound(balanceModel)
    {
        if (this._isRoundStarted) return;
        this._isRoundStarted = true;
        this._gameData = null;
        this.resetWin();
        this.lockAutoGame();
        this.casinoRoundsIndicatorData.left -= 1;
        if (this.autoGame) this.autoGame.startSpin();

        const rawData = await Locator.network.bet(this.bet, true);
        if (!rawData) throw new Error('network problems');
        if (rawData.errors?.length > 0)
        {
            throw new BackendError('backend errors', rawData.errors);
        }

        this._gameData = this.constructor.createGameData(rawData);

        balanceModel.setBalance(rawData.balance.wallet);

        this.saveResponseToStorage(rawData);
    }

    /**
     * Credits win to balance after each spin (if not bonus).
     * @param {BalanceModel} balanceModel
     */
    afterRoundEnding(balanceModel)
    {
        this.addWinToBalance(balanceModel);
        this.checkAutoGame(balanceModel);
        this.resetWin();
        this.unlockAutoGame();
    }

    addWinToBalance(balanceModel){
        if (this.gameData.preventAddBalance) return;
        balanceModel.add(this._win);
    }

    // added in order to not to loss the last win
    beforeExit(balanceModel) {
        this.addWinToBalance(balanceModel);
    }
}
