package com.tiedup.remake.network.cell;

import com.tiedup.remake.cells.CellDataV2;
import com.tiedup.remake.cells.CellRegistryV2;
import com.tiedup.remake.core.SystemMessageManager;
import com.tiedup.remake.core.TiedUpMod;
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.minecraftforge.network.NetworkEvent;

/**
 * Packet to rename a cell.
 * Client -> Server
 */
public class PacketRenameCell {

    private final UUID cellId;
    private final String newName;

    public PacketRenameCell(UUID cellId, String newName) {
        this.cellId = cellId;
        this.newName = newName;
    }

    public static void encode(PacketRenameCell msg, FriendlyByteBuf buf) {
        buf.writeUUID(msg.cellId);
        buf.writeUtf(msg.newName, 64);
    }

    public static PacketRenameCell decode(FriendlyByteBuf buf) {
        UUID cellId = buf.readUUID();
        String newName = buf.readUtf(64);
        return new PacketRenameCell(cellId, newName);
    }

    public static void handle(
        PacketRenameCell msg,
        Supplier<NetworkEvent.Context> ctx
    ) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer sender = ctx.get().getSender();
                if (sender == null) return;
                if (!PacketRateLimiter.allowPacket(sender, "action")) return;

                CellRegistryV2 registry = CellRegistryV2.get(
                    sender.serverLevel()
                );
                CellDataV2 cell = registry.getCell(msg.cellId);

                if (cell == null) {
                    TiedUpMod.LOGGER.debug(
                        "[PacketRenameCell] Cell not found: {}",
                        msg.cellId
                    );
                    return;
                }

                // Verify ownership
                if (
                    !cell.canPlayerManage(
                        sender.getUUID(),
                        sender.hasPermissions(2)
                    )
                ) {
                    TiedUpMod.LOGGER.debug(
                        "[PacketRenameCell] Player is not cell owner"
                    );
                    return;
                }

                // Sanitize name
                String sanitizedName = msg.newName.trim();
                if (sanitizedName.length() > 32) {
                    sanitizedName = sanitizedName.substring(0, 32);
                }

                // Set name (null to clear)
                cell.setName(sanitizedName.isEmpty() ? null : sanitizedName);
                registry.setDirty();

                SystemMessageManager.sendToPlayer(
                    sender,
                    SystemMessageManager.MessageCategory.CELL_RENAMED,
                    sanitizedName.isEmpty() ? "(cleared)" : sanitizedName
                );

                TiedUpMod.LOGGER.info(
                    "[PacketRenameCell] {} renamed cell {} to '{}'",
                    sender.getName().getString(),
                    msg.cellId.toString().substring(0, 8),
                    sanitizedName
                );
            });

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