namespace PkmnLib.Plugin.Gen7.Scripts.Status;

[Script(ScriptCategory.Status, "poisoned")]
public class Poisoned : Script, IScriptOnEndTurn, IAIInfoScriptExpectedEndOfTurnDamage
{
    private IPokemon? _pokemon;

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

    public virtual float GetPoisonMultiplier() => 1f / 8f;

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

        var damage = (uint)(_pokemon.MaxHealth * GetPoisonMultiplier());
        if (damage == 0)
            damage = 1;

        var battleData = _pokemon.BattleData;
        var args = new CustomTriggers.PoisonedDamageArgs(_pokemon, damage);
        _pokemon.RunScriptHook<IScriptCustomTrigger>(x => x.CustomTrigger(CustomTriggers.PoisonedDamage, args));

        var eventBatchId = new EventBatchId();
        battleData?.Battle.EventHook.Invoke(new DialogEvent("poisoned_damage", new Dictionary<string, object>
        {
            { "pokemon", _pokemon },
            { "damage", damage },
        })
        {
            BatchId = eventBatchId,
        });

        if (args.Invert)
            _pokemon.Heal(damage, batchId: eventBatchId);
        else
            _pokemon.Damage(damage, DamageSource.Status, eventBatchId);
    }

    /// <inheritdoc />
    public virtual void ExpectedEndOfTurnDamage(IPokemon pokemon, ref int damage)
    {
        if (_pokemon != null)
            damage += (int)(_pokemon.MaxHealth * GetPoisonMultiplier());
    }
}