namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Harvest is an ability that may restore a consumed Berry at the end of each turn.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Harvest_(Ability)">Bulbapedia - Harvest</see>
/// </summary>
[Script(ScriptCategory.Ability, "harvest")]
public class Harvest : 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.HeldItem is not null)
            return;

        var consumedBerry = _pokemon.BattleData.ConsumedItems.FirstOrDefault(x => x.Category == ItemCategory.Berry);
        if (consumedBerry != null)
        {
            var rng = battle.Random;
            if (battle.WeatherName != ScriptUtils.ResolveName<Weather.HarshSunlight>() && rng.GetInt(1) != 0)
                return;
            battle.EventHook.Invoke(new AbilityTriggerEvent(_pokemon));
            _ = _pokemon.ForceSetHeldItem(consumedBerry);
        }
    }
}