using Cysharp.Threading.Tasks;
using UnityEngine;
using YachtDice.Modifiers.Core;
using YachtDice.Modifiers.Definition;
using YachtDice.Modifiers.Runtime;

namespace YachtDice.Modifiers.Effects
{
    [CreateAssetMenu(fileName = "AddPerDieEffect", menuName = "YachtDice/Modifiers/Effects/Add Per Die")]
    public class AddPerDieEffect : Effect
    {
        [Tooltip("Points to add per matching die.")]
        [SerializeField] private int valuePerDie;

        [Tooltip("Die face value to match (1-6). 0 = any/all dice.")]
        [SerializeField, Range(0, 6)] private int targetDieValue;

        public override UniTask Apply(ModifierContext context, ModifierInstance instance)
        {
            if (context.DiceValues == null) return UniTask.CompletedTask;

            int count = 0;
            for (int i = 0; i < context.DiceValues.Length; i++)
            {
                if (targetDieValue == 0 || context.DiceValues[i] == targetDieValue)
                    count++;
            }

            context.FlatBonus += valuePerDie * count * instance.Stacks;
            return UniTask.CompletedTask;
        }

#if UNITY_EDITOR
        public static AddPerDieEffect CreateForTest(int valuePerDie, int targetDieValue = 0,
            ModifierPhase phase = ModifierPhase.Additive, int priority = 0)
        {
            var so = CreateInstance<AddPerDieEffect>();
            so.valuePerDie = valuePerDie;
            so.targetDieValue = targetDieValue;
            so.SetPhaseForTest(phase);
            so.SetPriorityForTest(priority);
            return so;
        }
#endif
    }
}
