import { InitResp } from '../../types/api';

export type FeatureMultipliers = { bonusBuy: number; freespinBuy: number; bonusChance: number };

export class FeatureMultiplierCalculator
{
    /**
     * Calculates feature purchase multipliers using backend init payload.
     * Ensures Bonus Chance falls back to neutral multiplier when data is missing.
     */
    calc(raw: InitResp): FeatureMultipliers
    {
        const featureOptions = raw?.options?.feature_options;
        const data = featureOptions?.feature_multipliers;

        if (!data)
        {
            return this.createFallbackMultipliers();
        }

        const divider = this.resolveDivider(featureOptions?.feature_multipliers?.base_bet);

        return {
            bonusBuy: this.toMultiplier(data.bonus_buy, divider),
            freespinBuy: this.toMultiplier(data.freespin_buy, divider),
            bonusChance: this.toBonusChanceMultiplier(data.bonus_chance, divider),
        };
    }

    /**
     * Provides defaults when backend omits feature multiplier data.
     */
    private createFallbackMultipliers(): FeatureMultipliers
    {
        return { bonusBuy: 0, freespinBuy: 0, bonusChance: 1 };
    }

    /**
     * Returns the divider used to translate absolute prices into multipliers.
     */
    private resolveDivider(baseBet: unknown): number
    {
        const baseBetValue = Number(baseBet);

        return Number.isFinite(baseBetValue) && baseBetValue > 0 ? baseBetValue : 100;
    }

    /**
     * Converts absolute feature prices into multiplier ratios.
     */
    private toMultiplier(value: unknown, divider: number): number
    {
        const numeric = Number(value);

        return Number.isFinite(numeric) ? numeric / divider : 0;
    }

    /**
     * Normalizes bonus chance multiplier ensuring it never drops below 1.
     */
    private toBonusChanceMultiplier(value: unknown, divider: number): number
    {
        const multiplier = this.toMultiplier(value, divider);

        return Math.max(multiplier, 1);
    }
}
