namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Healer is an ability that may heal an ally's status condition at the end of each turn in a double battle.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Healer_(Ability)">Bulbapedia - Healer</see>
/// </summary>
[Script(ScriptCategory.Ability, "healer")]
public class Healer : Script, IScriptOnEndTurn
{
    private IPokemon? _pokemon;

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

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

        if (_pokemon.BattleData.Position > 0)
        {
            var leftAlly = _pokemon.BattleData.BattleSide.Pokemon[_pokemon.BattleData.Position - 1];
            TryClearStatus(battle, leftAlly);
        }
        if (_pokemon.BattleData.Position < _pokemon.BattleData.BattleSide.Pokemon.Count - 1)
        {
            var rightAlly = _pokemon.BattleData.BattleSide.Pokemon[_pokemon.BattleData.Position + 1];
            TryClearStatus(battle, rightAlly);
        }
    }

    private static void TryClearStatus(IBattle battle, IPokemon? leftAlly)
    {
        if (leftAlly is null)
            return;
        if (leftAlly.StatusScript.IsEmpty)
            return;
        var rng = battle.Random;
        if (rng.GetInt(3) != 0) // 1 in 3 chance to heal
            return;
        battle.EventHook.Invoke(new AbilityTriggerEvent(leftAlly));
        leftAlly.ClearStatus();
    }
}