package com.tiedup.remake.network.minigame;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.minigame.LockpickMiniGameState;
import com.tiedup.remake.minigame.LockpickSessionManager;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 *
 * Contains:
 * - Session UUID
 * - New position (0.0 to 1.0)
 */
public class PacketLockpickMiniGameMove {

    private final UUID sessionId;
    private final float newPosition;

    public PacketLockpickMiniGameMove(UUID sessionId, float newPosition) {
        this.sessionId = sessionId;
        this.newPosition = newPosition;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(sessionId);
        buf.writeFloat(newPosition);
    }

    public static PacketLockpickMiniGameMove decode(FriendlyByteBuf buf) {
        UUID sessionId = buf.readUUID();
        float newPosition = buf.readFloat();
        return new PacketLockpickMiniGameMove(sessionId, newPosition);
    }

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

                // Rate limiting: Prevent lockpick spam
                if (
                    !com.tiedup.remake.network.PacketRateLimiter.allowPacket(
                        player,
                        "minigame"
                    )
                ) {
                    return;
                }

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

    private void handleServer(ServerPlayer player) {
        LockpickSessionManager manager = LockpickSessionManager.getInstance();

        // Validate session
        if (!manager.validateLockpickSession(player.getUUID(), sessionId)) {
            TiedUpMod.LOGGER.warn(
                "[PacketLockpickMiniGameMove] Invalid session {} for player {}",
                sessionId.toString().substring(0, 8),
                player.getName().getString()
            );
            return;
        }

        LockpickMiniGameState session = manager.getLockpickSession(
            player.getUUID()
        );
        if (session == null || session.isComplete()) {
            return;
        }

        // Update position (server-side validation: clamp to 0-1)
        session.setCurrentPosition(Math.max(0.0f, Math.min(1.0f, newPosition)));
    }
}
