const adminManager = require("../../game/AdminManager");

module.exports = (io, socket) => {
  if (!adminManager.io) adminManager.init(io);

  const handleAdminCommand = async ({ command }) => {
    const args = command.trim().split(/\s+/);
    const cmd = args[0].toLowerCase();

    try {
      switch (cmd) {
        case "/give": {
          const [_, targetName, itemId, amountStr] = args;
          const amount = parseInt(amountStr) || 1;

          if (!targetName || !itemId) {
            throw new Error("Usage: /give [player] [item] [amount]");
          }

          const result = await adminManager.giveItem(
            targetName,
            itemId,
            amount,
          );
          socket.emit(
            "admin:log",
            `Successfully gave ${result.amount}x [${result.itemId}] to ${result.targetName}.`,
          );
          break;
        }

        case "/clear": {
          const [_, targetName] = args;
          if (!targetName) throw new Error("Usage: /clear [player]");

          const target = await adminManager.clearInventory(targetName);
          socket.emit("admin:log", `Inventory for ${target} has been wiped.`);
          break;
        }

        case "/reload_data": {
          socket.emit("admin:log", "Reloading all datapacks...");
          await adminManager.reloadData();
          break;
        }

        default:
          socket.emit("admin:log", `Unknown admin command: ${cmd}`);
      }
    } catch (err) {
      socket.emit("admin:log", `Error: ${err.message}`);
    }
  };

  socket.on("admin:command", handleAdminCommand);
};
