package com.tiedup.remake.network.action;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 * v2.5: Packet to set the knife cut target accessory slot (Client to Server).
 *
 * When player clicks "Cut" on a locked accessory in StruggleChoiceScreen,
 * this packet stores which slot they want to cut. The player must then
 * right-click with a knife to start the cutting process.
 */
public class PacketSetKnifeCutTarget {

    private final BodyRegionV2 targetRegion;

    public PacketSetKnifeCutTarget(BodyRegionV2 targetRegion) {
        this.targetRegion = targetRegion;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeEnum(targetRegion);
    }

    public static PacketSetKnifeCutTarget decode(FriendlyByteBuf buf) {
        BodyRegionV2 region = buf.readEnum(BodyRegionV2.class);
        return new PacketSetKnifeCutTarget(region);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer player = ctx.get().getSender();
                if (player == null) {
                    return;
                }
                handleServer(player);
            });
        ctx.get().setPacketHandled(true);
    }

    private void handleServer(ServerPlayer player) {
        if (!PacketRateLimiter.allowPacket(player, "action")) return;

        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            return;
        }

        // Direct V2: PlayerBindState now uses BodyRegionV2 natively
        state.setKnifeCutTarget(targetRegion);

        TiedUpMod.LOGGER.debug(
            "[PacketSetKnifeCutTarget] {} set knife cut target to region {}",
            player.getName().getString(),
            targetRegion
        );
    }
}
