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);
    if (!player) return {};

    const slots = [
      "personal_helmet",
      "personal_suit",
      "personal_gloves",
      "personal_backpack",
      "personal_boots",
      "personal_weapons",
      "ship_hull",
      "ship_shields",
      "ship_engines",
    ];

    const equipment = {};
    slots.forEach((slot) => {
      equipment[slot] = player[`equipped_${slot}`] || null;
    });
    return 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 dbField = `equipped_${slot}`.replace("original:", "");
    await Player.update({ [dbField]: itemId }, { where: { id: playerId } });
    return itemInfo;
  }

  async unequipItem(playerId, slot) {
    const dbField = `equipped_${slot}`;
    await Player.update({ [dbField]: null }, { where: { id: playerId } });
    return true;
  }
}

module.exports = new InventoryManager();
