package com.tiedup.remake.network.bounty;

import com.tiedup.remake.bounty.BountyManager;
import com.tiedup.remake.core.SystemMessageManager;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet: Client requests to delete/cancel a bounty.
 *
 *
 * Only the bounty client or an admin can delete.
 * If client deletes, reward is returned.
 */
public class PacketDeleteBounty {

    private final String bountyId;

    public PacketDeleteBounty(String bountyId) {
        this.bountyId = bountyId;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeUtf(bountyId);
    }

    public static PacketDeleteBounty decode(FriendlyByteBuf buf) {
        return new PacketDeleteBounty(buf.readUtf(256));
    }

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

                BountyManager manager = BountyManager.get(player.serverLevel());
                boolean success = manager.cancelBounty(player, bountyId);

                if (!success) {
                    SystemMessageManager.sendToPlayer(
                        player,
                        SystemMessageManager.MessageCategory.ERROR,
                        "Cannot delete this bounty."
                    );
                }

                TiedUpMod.LOGGER.debug(
                    "[BOUNTY] Delete request from {}: bounty={}, success={}",
                    player.getName().getString(),
                    bountyId,
                    success
                );
            });
        ctx.get().setPacketHandled(true);
    }
}
