using System;
using System.Collections.Generic;
using System.Linq;

namespace RolemasterDb.App.Features;

public static class RolemasterRoller
{
    public static LookupRollResult RollAttack(Random random) =>
        RollOpenEndedHigh(random);

    public static LookupRollResult RollCritical(Random random, CriticalTableReference? table) =>
        AllowsOpenEndedCritical(table)
            ? RollOpenEndedHigh(random)
            : RollStandard(random);

    public static bool AllowsOpenEndedCritical(CriticalTableReference? table) =>
        table is not null &&
        table.RollBands.Any(item => item.MinRoll > 100 || item.MaxRoll is null || item.MaxRoll > 100);

    public static LookupRollResult RollStandard(Random random)
    {
        var roll = random.Next(1, 101);
        return new LookupRollResult(roll, [roll]);
    }

    public static LookupRollResult RollOpenEndedHigh(Random random)
    {
        var rolls = new List<int>();
        var total = 0;

        while (true)
        {
            var roll = random.Next(1, 101);
            rolls.Add(roll);
            total += roll;

            if (roll < 96)
            {
                break;
            }
        }

        return new LookupRollResult(total, rolls);
    }
}
