
export type PricingTier = {
    selected: boolean
    price: number
    hours: number
    payout: number
    custom_discount: number
    min: number
    max: number
}

export const getDefaultFirstTier = (maxAttendees: number): PricingTier => {
    return {
        selected: true,
        price: 0,
        hours: 0,
        payout: 0,
        custom_discount: 0,
        min: 1,
        max: maxAttendees
    }
}

export const calculateNetPayout = (price: number, discount: number = 0) => {
    const flatPrice = (price * 12) - (price * 12) * (discount / 100);
    const serviceFee = (flatPrice * 0.15);
    const VAT = (serviceFee * 0.15);
    return Math.max(0, flatPrice - serviceFee - VAT);
}

export const maintainValidPricingTiers = (tiers: PricingTier[], maxAttendees: number, uniformPricing: boolean) => {

    if(tiers.length === 0) {
        tiers.push(getDefaultFirstTier(maxAttendees));
    }

    if(uniformPricing) {
        tiers.splice(1, tiers.length);
        tiers[0].max = maxAttendees;
    }

    let i = 0;
    let correct = false;
    while (!correct) {
        const t0 = tiers[i];
        const t1 = tiers[i + 1];

        t0.payout = calculateNetPayout(t0.price, t0.custom_discount);

        if(t1) {
            // The next tier min should start from the current one's max
            if(t0.max !== t1.min - 1) {
                t1.min = t0.max + 1;
            }

            if(t1.min >= t1.max) {
                tiers.splice(i + 1, 1);
                i--;
            }

        } else if(t0.max < maxAttendees) {
            tiers.push({
                ...t0,
                min: t0.max + 1,
                max: maxAttendees
            });
        }

        if(i >= tiers.length - 1) {
            correct = true;
        }

        i++;
    }
}

export const getMinMaxFromPricingTiers = (tiers: PricingTier[]) => {
    if(tiers.length === 0) {
        return { min: 0, max: 0 };
    }

    const minMax = { min: Infinity, max: -Infinity };

    for(let tier of tiers) {
        if(tier.price > minMax.max) {
            minMax.max = tier.price;
        }
        if(tier.price < minMax.min) {
            minMax.min = tier.price;
        }
    }

    return minMax;
}