namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Ice Body is an ability that heals the Pokémon for 1/16 of its maximum HP each turn during hail.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Ice_Body_(Ability)">Bulbapedia - Ice Body</see>
/// </summary>
[Script(ScriptCategory.Ability, "ice_body")]
public class IceBody : Script, IScriptOnEndTurn, IScriptCustomTrigger
{
    private IPokemon? _pokemon;

    /// <inheritdoc />
    public override void OnAddedToParent(IScriptSource source)
    {
        if (source is not IPokemon pokemon)
            throw new InvalidOperationException("Ice Body can only be added to a Pokemon script source.");
        _pokemon = pokemon;
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        if (_pokemon is null)
            return;

        // Check if the weather is hail
        if (battle.WeatherName != ScriptUtils.ResolveName<Weather.Hail>())
            return;

        // Heal the Pokémon for 1/16 of its maximum HP
        EventBatchId batchId = new();
        var healAmount = _pokemon.MaxHealth / 16;
        _pokemon.Heal(healAmount, true, batchId);

        // Trigger the ability event
        battle.EventHook.Invoke(new AbilityTriggerEvent(_pokemon)
        {
            BatchId = batchId,
        });
    }

    /// <inheritdoc />
    public void CustomTrigger(StringKey eventName, ICustomTriggerArgs args)
    {
        if (eventName != CustomTriggers.IgnoreHail || args is not CustomTriggers.IgnoreHailArgs ignoreHailArgs)
            return;
        ignoreHailArgs.Ignore = true;
    }
}