package com.tiedup.remake.v2.bondage.network;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.v2.BodyRegionV2;
import com.tiedup.remake.v2.bondage.IV2BondageItem;
import com.tiedup.remake.v2.bondage.capability.V2EquipmentHelper;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.network.NetworkEvent;

/**
 * C2S packet: player requests removal of a V2 bondage item from themselves.
 *
 * Validates:
 * - Region is occupied
 * - Item canUnequip (not locked)
 * - ARMS not occupied (can't manipulate buckles with bound arms)
 * - Item does not occupy ARMS (arm restraints require struggle, not manual removal)
 */
public class PacketV2SelfRemove {

    private final BodyRegionV2 region;

    public PacketV2SelfRemove(BodyRegionV2 region) {
        this.region = region;
    }

    public static void encode(PacketV2SelfRemove msg, FriendlyByteBuf buf) {
        buf.writeEnum(msg.region);
    }

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

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

            handleServer(player, msg.region);
        });
        ctx.setPacketHandled(true);
    }

    private static void handleServer(ServerPlayer player, BodyRegionV2 region) {
        ItemStack stack = V2EquipmentHelper.getInRegion(player, region);
        if (stack.isEmpty()) return;

        if (!(stack.getItem() instanceof IV2BondageItem item)) return;

        // Arm restraints cannot be self-removed — must use struggle
        if (item.getOccupiedRegions(stack).contains(BodyRegionV2.ARMS)) {
            TiedUpMod.LOGGER.debug(
                "[V2SelfRemove] Blocked: item occupies ARMS, must struggle"
            );
            return;
        }

        // Cannot manipulate buckles/clasps with bound arms
        if (V2EquipmentHelper.isRegionOccupied(player, BodyRegionV2.ARMS)) {
            TiedUpMod.LOGGER.debug(
                "[V2SelfRemove] Blocked: player's ARMS are occupied"
            );
            return;
        }

        // Cannot manipulate buckles/clasps with covered hands
        if (V2EquipmentHelper.isRegionOccupied(player, BodyRegionV2.HANDS)) {
            TiedUpMod.LOGGER.debug(
                "[V2SelfRemove] Blocked: player's HANDS are occupied"
            );
            return;
        }

        // Check item allows unequip (not locked)
        if (!item.canUnequip(stack, player)) {
            TiedUpMod.LOGGER.debug(
                "[V2SelfRemove] Blocked: item canUnequip=false (locked?)"
            );
            return;
        }

        // Remove and give to inventory
        ItemStack removed = V2EquipmentHelper.unequipFromRegion(player, region);
        if (!removed.isEmpty()) {
            if (!player.getInventory().add(removed)) {
                player.drop(removed, false);
            }
        }
        // sync() is called inside unequipFromRegion
    }
}
