namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Download is an ability that raises the Pokémon's Attack or Special Attack stat when it enters battle,
/// depending on which stat is lower on the opposing Pokémon.
/// This ability is commonly associated with Porygon and its evolutions.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Download_(Ability)">Bulbapedia - Download</see>
/// </summary>
[Script(ScriptCategory.Ability, "download")]
public class Download : Script, IScriptOnSwitchIn
{
    /// <inheritdoc />
    public void OnSwitchIn(IPokemon pokemon, byte position)
    {
        var battleData = pokemon.BattleData;
        if (battleData == null)
            return;

        var opponents = battleData.Battle.Sides.Where(x => x != battleData.BattleSide).SelectMany(x => x.Pokemon)
            .WhereNotNull().ToArray();
        if (opponents.Length == 0)
            return;
        var opponentAverageDefense = opponents.Average(x => x.BoostedStats.Defense);
        var opponentAverageSpecialDefense = opponents.Average(x => x.BoostedStats.SpecialDefense);

        EventBatchId batchId = new();
        battleData.Battle.EventHook.Invoke(new AbilityTriggerEvent(pokemon)
        {
            BatchId = batchId,
        });
        pokemon.ChangeStatBoost(
            opponentAverageDefense < opponentAverageSpecialDefense ? Statistic.Attack : Statistic.SpecialAttack, 1,
            true, false, batchId);
    }
}