namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "beat_up")]
public class BeatUp : Script, IScriptChangeNumberOfHits, IScriptChangeBasePower
{
    private IPokemon[]? _relevantPartyMembers;

    private static IEnumerable<IPokemon> GetRelevantPartyMembers(IPokemon user)
    {
        var battleData = user.BattleData;
        if (battleData == null)
            return [];

        var party = battleData.Battle.Parties.FirstOrDefault(x => x.Party.Contains(user));
        return party?.Party.WhereNotNull().Where(x => x.IsUsable && x.StatusScript.IsEmpty) ?? [];
    }

    /// <inheritdoc />
    public void ChangeNumberOfHits(IMoveChoice choice, ref byte numberOfHits)
    {
        var relevantPartyMembers = _relevantPartyMembers ??= GetRelevantPartyMembers(choice.User).ToArray();

        numberOfHits = (byte)relevantPartyMembers.Count();
        if (numberOfHits == 0)
            numberOfHits = 1;
    }

    /// <inheritdoc />
    public void ChangeBasePower(IExecutingMove move, IPokemon target, byte hit, ref ushort basePower)
    {
        var relevantPartyMembers = _relevantPartyMembers ??= GetRelevantPartyMembers(move.User).ToArray();
        var hittingPokemon = relevantPartyMembers.ElementAtOrDefault(hit);
        if (hittingPokemon == null)
            return;

        basePower = (byte)(hittingPokemon.Form.BaseStats.Attack / 10 + 5);
    }
}