namespace PkmnLib.Plugin.Gen7.Scripts.Terrain;

[Script(ScriptCategory.Terrain, "grassy_terrain")]
public class GrassyTerrain : Script, IScriptChangeBasePower, IScriptOnEndTurn
{
    private static bool IsAffectedByTerrain(IPokemon pokemon) =>
        !pokemon.IsFloating;

    /// <inheritdoc />
    public void ChangeBasePower(IExecutingMove move, IPokemon target, byte hit, ref ushort basePower)
    {
        // It boosts the power of Grass-type moves used by affected Pokémon by 50% (regardless of whether the target of
        // the move is affected by Grassy Terrain).
        if (IsAffectedByTerrain(move.User))
        {
            var type = move.GetHitData(target, hit).Type;
            if (type?.Name == "grass")
            {
                basePower = basePower.MultiplyOrMax(1.5f);
            }
        }

        // The power of Bulldoze, Earthquake, and Magnitude is halved against affected targets (regardless of whether the
        // user of the move is affected by Grassy Terrain).
        if (IsAffectedByTerrain(target))
        {
            var moveName = move.UseMove.Name;
            if (moveName == "bulldoze" || moveName == "earthquake" || moveName == "magnitude")
            {
                basePower /= 2;
            }
        }
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        // At the end of each turn, Grassy Terrain restores 1/16 of the maximum HP of each affected Pokémon.
        foreach (var pokemon in battle.Sides.SelectMany(x => x.Pokemon).WhereNotNull())
        {
            if (!IsAffectedByTerrain(pokemon) || pokemon.IsFainted)
                continue;

            var healing = pokemon.MaxHealth / 16f;
            pokemon.Heal((uint)healing);
        }
    }
}