package com.tiedup.remake.network.merchant;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.entities.EntityKidnapperMerchant;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.UUID;
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;

/**
 * Packet sent from client to server when player closes the merchant trading screen.
 *
 * Contains:
 * - Merchant entity ID
 */
public class PacketCloseMerchantScreen {

    private final UUID merchantUUID;

    /**
     * Create packet to notify merchant screen closed.
     *
     * @param merchantUUID The UUID of the merchant entity (persistent across restarts)
     */
    public PacketCloseMerchantScreen(UUID merchantUUID) {
        this.merchantUUID = merchantUUID;
    }

    /**
     * Encode the packet to the network buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(merchantUUID);
    }

    /**
     * Decode the packet from the network buffer.
     */
    public static PacketCloseMerchantScreen decode(FriendlyByteBuf buf) {
        UUID uuid = buf.readUUID();
        return new PacketCloseMerchantScreen(uuid);
    }

    /**
     * Handle the packet on the receiving side (SERVER SIDE).
     */
    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);
    }

    /**
     * Handle the packet on the server side.
     * Marks that the player is no longer trading with the merchant.
     */
    private void handleServer(ServerPlayer player) {
        if (!PacketRateLimiter.allowPacket(player, "action")) return;

        // Find the merchant entity by UUID (persistent across restarts)
        Entity entity = (
            (net.minecraft.server.level.ServerLevel) player.level()
        ).getEntity(merchantUUID);
        if (!(entity instanceof EntityKidnapperMerchant merchant)) {
            TiedUpMod.LOGGER.warn(
                "[PacketCloseMerchantScreen] Entity {} is not a merchant or not found",
                merchantUUID
            );
            return;
        }

        // Teardown must not gate on distance — the merchant may have moved
        // out of range while the screen was open, and blocking cleanup
        // would permanently leak the player's entry in tradingPlayers.
        merchant.stopTrading(player.getUUID());
    }
}
