using PkmnLib.Plugin.Gen7.Scripts.Pokemon;

namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "counter")]
public class Counter : Script, IScriptOnBeforeTurnStart, IScriptChangeTargets, IScriptChangeMoveDamage
{
    /// <inheritdoc />
    public void OnBeforeTurnStart(ITurnChoice choice)
    {
        choice.User.Volatile.Add(new CounterHelperEffect());
    }

    /// <inheritdoc />
    public void ChangeTargets(IMoveChoice moveChoice, ref IReadOnlyList<IPokemon?> targets)
    {
        var counterHelper = moveChoice.User.Volatile.Get<CounterHelperEffect>();
        var lastHitBy = counterHelper?.LastHitBy;
        if (lastHitBy == null)
        {
            moveChoice.Fail();
            return;
        }
        targets = [lastHitBy];
    }

    /// <inheritdoc />
    public void ChangeMoveDamage(IExecutingMove move, IPokemon target, byte hit, ref uint damage)
    {
        var counterHelper = move.User.Volatile.Get<CounterHelperEffect>();
        if (counterHelper == null || counterHelper.LastHitBy == null || counterHelper.LastHitBy != target)
        {
            move.GetHitData(target, hit).Fail();
            return;
        }
        var lastDamage = counterHelper.LastDamage;
        damage = lastDamage.MultiplyOrMax(2);
    }
}