const { Player, Inventory } = require("../models");
const DatapackLoader = require("./DatapackLoader");

class InventoryManager {
  async getInventory(playerId) {
    return await Inventory.findAll({
      where: { playerId },
      attributes: ["itemId", "quantity"],
    });
  }

  async getEquipment(playerId) {
    const player = await Player.findByPk(playerId);
    return player ? player.equipment : {};
  }

  async equipItem(playerId, itemId, slot) {
    const hasItem = await Inventory.findOne({ where: { playerId, itemId } });
    if (!hasItem) throw new Error("ITEM_NOT_FOUND");

    const itemInfo = DatapackLoader.getItem(itemId);
    if (!itemInfo) throw new Error("INVALID_ITEM_DATA");

    const allowedSlot = itemInfo.meta?.equipmentSlot;
    if (allowedSlot !== slot) {
      throw new Error("INVALID_SLOT_FOR_ITEM");
    }

    const player = await Player.findByPk(playerId);
    if (!player) throw new Error("PLAYER_NOT_FOUND");

    const currentEquip = player.equipment;
    currentEquip[slot] = itemId;

    player.equipment = currentEquip;
    player.changed("equipment", true);
    await player.save();

    return itemInfo;
  }

  async unequipItem(playerId, slot) {
    const player = await Player.findByPk(playerId);
    if (!player) throw new Error("PLAYER_NOT_FOUND");

    const currentEquip = player.equipment;
    if (currentEquip[slot]) {
      delete currentEquip[slot];
      player.equipment = currentEquip;
      player.changed("equipment", true);
      await player.save();
    }

    return true;
  }
}

module.exports = new InventoryManager();
