package com.tiedup.remake.network.master;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.dialogue.conversation.PetRequest;
import com.tiedup.remake.dialogue.conversation.PetRequestManager;
import com.tiedup.remake.entities.EntityMaster;
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;

/**
 * Packet sent from client to server when player selects a pet request option.
 *
 * Direction: Client → Server (C2S)
 *
 * Contains:
 * - Master entity ID
 * - Request type (enum name)
 */
public class PacketPetRequest {

    /** Maximum distance for request interaction */
    private static final double MAX_DISTANCE = 8.0;

    private final int entityId;
    private final String requestName;

    /**
     * Create a pet request packet.
     *
     * @param entityId The master entity ID
     * @param request The request type
     */
    public PacketPetRequest(int entityId, PetRequest request) {
        this.entityId = entityId;
        this.requestName = request.name();
    }

    private PacketPetRequest(int entityId, String requestName) {
        this.entityId = entityId;
        this.requestName = requestName;
    }

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

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

    /**
     * Handle the packet on server side.
     */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer sender = ctx.get().getSender();
                if (sender == null) return;

                handleServer(sender);
            });
        ctx.get().setPacketHandled(true);
    }

    private void handleServer(ServerPlayer sender) {
        // MEDIUM FIX: Rate limiting to prevent pet request spam
        if (!PacketRateLimiter.allowPacket(sender, "action")) {
            return;
        }

        // Find the master entity
        Entity entity = sender.level().getEntity(entityId);
        if (entity == null) {
            TiedUpMod.LOGGER.warn(
                "[PacketPetRequest] Entity {} not found",
                entityId
            );
            return;
        }

        if (!(entity instanceof EntityMaster master)) {
            TiedUpMod.LOGGER.warn(
                "[PacketPetRequest] Entity {} is not a Master",
                entityId
            );
            return;
        }

        // Validate distance
        double distance = sender.distanceTo(entity);
        if (distance > MAX_DISTANCE) {
            TiedUpMod.LOGGER.warn(
                "[PacketPetRequest] Player {} too far from master {} ({})",
                sender.getName().getString(),
                entityId,
                distance
            );
            return;
        }

        // Parse request
        PetRequest request;
        try {
            request = PetRequest.valueOf(requestName);
        } catch (IllegalArgumentException e) {
            TiedUpMod.LOGGER.warn(
                "[PacketPetRequest] Unknown request: {}",
                requestName
            );
            return;
        }

        TiedUpMod.LOGGER.info(
            "[PacketPetRequest] {} sent request {} to {}",
            sender.getName().getString(),
            request.name(),
            master.getNpcName()
        );

        // Handle the request
        PetRequestManager.handleRequest(master, sender, request);
    }

    public int getEntityId() {
        return entityId;
    }

    public String getRequestName() {
        return requestName;
    }
}
