package com.tiedup.remake.network.master;

import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet sent from server to client to open the pet request menu.
 *
 * Direction: Server → Client (S2C)
 *
 * Contains:
 * - Master entity ID
 * - Master name (for display)
 */
public class PacketOpenPetRequestMenu {

    private final int entityId;
    private final String masterName;

    /**
     * Create a packet to open the pet request menu.
     *
     * @param entityId The master entity ID
     * @param masterName The master's display name
     */
    public PacketOpenPetRequestMenu(int entityId, String masterName) {
        this.entityId = entityId;
        this.masterName = masterName;
    }

    /**
     * Encode the packet to buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(entityId);
        buf.writeUtf(masterName, 64);
    }

    /**
     * Decode the packet from buffer.
     */
    public static PacketOpenPetRequestMenu decode(FriendlyByteBuf buf) {
        int entityId = buf.readInt();
        String masterName = buf.readUtf(64);
        return new PacketOpenPetRequestMenu(entityId, masterName);
    }

    /**
     * Handle the packet on the network thread.
     */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> handleClient());
        ctx.get().setPacketHandled(true);
    }

    /**
     * Client-side handling.
     * This method is only called on the client, avoiding class loading issues.
     */
    private void handleClient() {
        // Delegate to client-only helper to avoid class loading on server
        com.tiedup.remake.client.network.ClientPacketHandler.openPetRequestScreen(
            entityId,
            masterName
        );
    }

    public int getEntityId() {
        return entityId;
    }

    public String getMasterName() {
        return masterName;
    }
}
