namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "flame_burst")]
public class FlameBurst : Script, IScriptOnSecondaryEffect
{
    /// <inheritdoc />
    public void OnSecondaryEffect(IExecutingMove move, IPokemon target, byte hit)
    {
        var adjacentFoes = GetAdjacentFoes(move.User).WhereNotNull();
        EventBatchId batchId = new();
        foreach (var adjacentFoe in adjacentFoes)
        {
            adjacentFoe.Damage(adjacentFoe.BoostedStats.Hp / 16, DamageSource.Misc, batchId);
        }
    }

    private static IEnumerable<IPokemon?> GetAdjacentFoes(IPokemon pokemon)
    {
        var battleData = pokemon.BattleData;
        if (battleData == null)
            yield break;
        if (battleData.Battle.PositionsPerSide == 1)
            yield break;

        var position = battleData.Position;
        var side = battleData.Battle.Sides[battleData.SideIndex];

        if (position == 0)
        {
            yield return side.Pokemon[1];
        }
        else
        {
            yield return side.Pokemon[position - 1];
            if (position < side.Pokemon.Count - 1)
                yield return side.Pokemon[position + 1];
        }
    }
}