package com.tiedup.remake.network.personality;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.entities.EntityDamsel;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.v2.BodyRegionV2;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet sent from client to server to request opening the NPC inventory screen.
 * Server responds with PacketOpenNpcInventory if validation passes.
 *
 * Personality System Phase J: NPC Inventory
 */
public class PacketRequestNpcInventory {

    private final java.util.UUID entityUUID; // HIGH FIX: use UUID for persistence

    /**
     * Create a request packet.
     *
     * @param entityUUID The NPC entity UUID
     */
    public PacketRequestNpcInventory(java.util.UUID entityUUID) {
        this.entityUUID = entityUUID;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(entityUUID); // HIGH FIX
    }

    public static PacketRequestNpcInventory decode(FriendlyByteBuf buf) {
        return new PacketRequestNpcInventory(buf.readUUID());
    }

    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;

                // HIGH FIX: lookup by UUID
                Entity entity = (
                    (net.minecraft.server.level.ServerLevel) player.level()
                ).getEntity(entityUUID);
                if (!(entity instanceof EntityDamsel damsel)) {
                    TiedUpMod.LOGGER.warn(
                        "[PacketRequestNpcInventory] Entity {} is not a damsel",
                        entityUUID
                    );
                    return;
                }

                // Verify player is nearby
                if (player.distanceTo(damsel) > 6.0) {
                    TiedUpMod.LOGGER.warn(
                        "[PacketRequestNpcInventory] Player {} too far from NPC",
                        player.getName().getString()
                    );
                    return;
                }

                // Verify player is owner of collar (or NPC has no collar)
                if (damsel.hasCollar()) {
                    ItemStack collar = damsel.getEquipment(BodyRegionV2.NECK);
                    if (com.tiedup.remake.v2.bondage.CollarHelper.isCollar(collar)) {
                        if (!com.tiedup.remake.v2.bondage.CollarHelper.isOwner(collar, player)) {
                            TiedUpMod.LOGGER.warn(
                                "[PacketRequestNpcInventory] Player {} is not owner of NPC collar",
                                player.getName().getString()
                            );
                            return;
                        }
                    }
                }

                // Open vanilla container via NetworkHooks
                TiedUpMod.LOGGER.debug(
                    "[PacketRequestNpcInventory] Opening inventory for {} to {}",
                    damsel.getNpcName(),
                    player.getName().getString()
                );

                net.minecraftforge.network.NetworkHooks.openScreen(
                    player,
                    damsel,
                    buf -> {
                        buf.writeInt(damsel.getId());
                        buf.writeInt(damsel.getNpcInventorySize());
                        buf.writeUtf(damsel.getNpcName(), 64);
                    }
                );
            });
        ctx.get().setPacketHandled(true);
    }
}
