const inventoryManager = require("../../game/InventoryManager");
const sessionManager = require("../../game/SessionManager");

module.exports = (io, socket) => {
  const userId = socket.user?.id;
  if (!userId) return;

  socket.on("player:get_inventory", async () => {
    try {
      const items = await inventoryManager.getInventory(userId);
      socket.emit("player:inventory_data", items);
    } catch (err) {
      socket.emit("error", { message: "LOAD_INVENTORY_FAILED" });
    }
  });

  socket.on("player:get_equipment", async () => {
    try {
      const equipment = await inventoryManager.getEquipment(userId);
      socket.emit("player:equipment_data", equipment);
    } catch (err) {
      console.error(err);
    }
  });

  socket.on("player:equip_item", async ({ itemId, slot }) => {
    try {
      const itemInfo = await inventoryManager.equipItem(userId, itemId, slot);

      sessionManager.updateEquipment(socket.id, slot, itemId);

      socket.emit("player:item_equipped", { slot, itemId });

      socket.broadcast.emit("player:visible_changed", {
        playerId: userId,
        slot,
        texturePath: itemInfo.texture,
      });
    } catch (err) {
      socket.emit("error", { message: err.message });
    }
  });

  socket.on("player:unequip_item", async ({ slot }) => {
    try {
      await inventoryManager.unequipItem(userId, slot);
      sessionManager.updateEquipment(socket.id, slot, null);

      socket.emit("player:item_unequipped", { slot });
      socket.broadcast.emit("player:visible_changed", {
        playerId: userId,
        slot,
        texturePath: null,
      });
    } catch (err) {
      console.error(err);
    }
  });
};
