namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Aftermath is an ability that causes the attacker to lose 1/4 of its maximum HP if it knocks out the user with a contact move.
/// This effect only triggers if the move that caused the faint was a contact move.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Aftermath_(Ability)">Bulbapedia - Aftermath</see>
/// </summary>
[Script(ScriptCategory.Ability, "aftermath")]
public class Aftermath : Script, IScriptOnIncomingHit, IScriptOnFaint
{
    private static readonly StringKey DampAbilityName = new("damp");

    private IExecutingMove? _lastAttack;

    /// <inheritdoc />
    public void OnIncomingHit(IExecutingMove move, IPokemon target, byte hit)
    {
        _lastAttack = move.GetHitData(target, hit).IsContact ? move : null;
    }

    /// <inheritdoc />
    public void OnFaint(IPokemon pokemon, DamageSource source)
    {
        if (source != DamageSource.MoveDamage)
            return;
        if (_lastAttack is null)
            return;
        var user = _lastAttack.User;
        if (!user.IsUsable)
            return;
        if (user.BattleData is null)
            return;

        // Aftermath does not trigger if a Pokémon with Damp is on the field
        var battle = user.BattleData.Battle;
        var hasDamp = battle.Sides.SelectMany(side => side.Pokemon).WhereNotNull()
            .Any(p => p.ActiveAbility?.Name == DampAbilityName);
        if (hasDamp)
            return;

        EventBatchId eventBatchId = new();
        battle.EventHook.Invoke(new AbilityTriggerEvent(pokemon)
        {
            BatchId = eventBatchId,
        });
        user.Damage(user.MaxHealth / 4, DamageSource.Misc, eventBatchId);
    }
}