package com.tiedup.remake.network.bounty;

import com.tiedup.remake.bounty.Bounty;
import com.tiedup.remake.bounty.BountyManager;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet: Client requests bounty list from server.
 *
 *
 * Flow: Client → Server → PacketSendBounties → Client
 */
public class PacketRequestBounties {

    public PacketRequestBounties() {}

    public void encode(FriendlyByteBuf buf) {
        // No data needed
    }

    public static PacketRequestBounties decode(FriendlyByteBuf buf) {
        return new PacketRequestBounties();
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer player = ctx.get().getSender();
                if (player == null) return;
                if (!PacketRateLimiter.allowPacket(player, "ui")) return;

                BountyManager manager = BountyManager.get(player.serverLevel());
                List<Bounty> bounties = manager.getBounties(
                    player.serverLevel()
                );
                boolean isAdmin = player.hasPermissions(2);

                // Send bounty list back to client
                ModNetwork.sendToPlayer(
                    new PacketSendBounties(bounties, isAdmin),
                    player
                );
            });
        ctx.get().setPacketHandled(true);
    }
}
