package com.tiedup.remake.network.conversation;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.dialogue.conversation.ConversationManager;
import com.tiedup.remake.entities.EntityDamsel;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkEvent;

/**
 * Client-to-Server packet: player closes conversation GUI.
 *
 * Split from the former bidirectional PacketEndConversation (H16 fix).
 */
public class PacketEndConversationC2S {

    private final int entityId;

    public PacketEndConversationC2S(int entityId) {
        this.entityId = entityId;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(entityId);
    }

    public static PacketEndConversationC2S decode(FriendlyByteBuf buf) {
        return new PacketEndConversationC2S(buf.readInt());
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer sender = ctx.get().getSender();
                if (sender == null) return;

                if (!PacketRateLimiter.allowPacket(sender, "action")) return;

                TiedUpMod.LOGGER.info(
                    "[PacketEndConversationC2S] {} ended conversation with entity {}",
                    sender.getName().getString(),
                    entityId
                );

                // Get the damsel entity to properly end with cooldown
                EntityDamsel damsel = null;
                Entity entity = sender.level().getEntity(entityId);
                if (entity instanceof EntityDamsel d) {
                    damsel = d;
                }

                // Teardown must not gate on distance — the damsel may have
                // moved out of range while the screen was open, and blocking
                // cleanup would leak the conversation entry permanently.
                ConversationManager.endConversation(sender, damsel);
            });
        ctx.get().setPacketHandled(true);
    }

    public int getEntityId() {
        return entityId;
    }
}
