using PkmnLib.Plugin.Gen7.Scripts.Utils;

namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "baton_pass")]
public class BatonPass : Script, IScriptOnSecondaryEffect
{
    /// <inheritdoc />
    public void OnSecondaryEffect(IExecutingMove move, IPokemon target, byte hit)
    {
        var user = move.User;
        var additionalData = move.MoveChoice.AdditionalData;
        if (additionalData == null)
            return;
        if (additionalData["to_switch"] is not IPokemon toSwitch)
            return;
        var battleData = user.BattleData;
        if (battleData == null)
            return;

        var statBoosts = user.StatBoost;
        var volatileScripts = user.Volatile.Select(x => x.Script).WhereNotNull().ToList();
        foreach (var container in user.Volatile)
        {
            container.ClearWithoutRemoving();
        }

        var side = battleData.Battle.Sides[battleData.SideIndex];
        side.SwapPokemon(battleData.Position, toSwitch);

        foreach (Statistic stat in Enum.GetValues(typeof(Statistic)))
        {
            toSwitch.StatBoost.SetStatistic(stat, statBoosts.GetStatistic(stat));
        }
        toSwitch.RecalculateBoostedStats();

        foreach (var script in volatileScripts)
        {
            if (script is not IBatonPassException)
                continue;
            toSwitch.Volatile.Add(script);
        }
    }
}