class SessionManager {
  constructor() {
    this.sessions = new Map(); // socket.id => session data
  }

  addPlayer(socketId, playerRaw) {
    this.sessions.set(socketId, {
      id: playerRaw.id,
      username: playerRaw.username,
      level: playerRaw.level,
      energy: playerRaw.energy,
      maxEnergy: playerRaw.maxEnergy,
      status: "docked",
      currentLocation: "Home_Base",
      scene: "world",
      sceneData: null,
      joinedAt: Date.now(),
      equipment: {
        personal_helmet: playerRaw.equipped_personal_helmet,
        personal_suit: playerRaw.equipped_personal_suit,
        personal_gloves: playerRaw.equipped_personal_gloves,
        personal_backpack: playerRaw.equipped_personal_backpack,
        personal_boots: playerRaw.equipped_personal_boots,
        personal_weapons: playerRaw.equipped_personal_weapons,

        ship_hull: playerRaw.equipped_ship_hull,
        ship_shields: playerRaw.equipped_ship_shields,
        ship_engines: playerRaw.equipped_ship_engines,
        ship_weapon_1: playerRaw.equipped_ship_weapon_1,
        ship_weapon_2: playerRaw.equipped_ship_weapon_2,
      },
    });
  }

  updateEquipment(socketId, slot, itemId) {
    const session = this.sessions.get(socketId);
    if (session && session.equipment.hasOwnProperty(slot)) {
      session.equipment[slot] = itemId;
    } else if (session) {
      session.equipment[slot] = itemId;
    }
  }

  setPlayerScene(socketId, sceneName, data = null) {
    const session = this.sessions.get(socketId);
    if (session) {
      session.scene = sceneName;
      session.sceneData = data;
      session.status = sceneName === "dungeon" ? "in_mission" : "active";
      console.log(`[Session] Player ${session.id} switched to ${sceneName}`);
    }
  }

  getPlayerSession(socketId) {
    return this.sessions.get(socketId);
  }

  updateStatus(socketId, newStatus, location = null) {
    const session = this.sessions.get(socketId);
    if (session) {
      session.status = newStatus;
      if (location) session.currentLocation = location;
    }
  }

  removePlayer(socketId) {
    this.sessions.delete(socketId);
  }

  getPlayer(socketId) {
    return this.sessions.get(socketId);
  }

  getPlayerByUserId(userId) {
    return Array.from(this.sessions.values()).find((s) => s.id === userId);
  }

  getAllOnline() {
    return Array.from(this.sessions.values());
  }
}

module.exports = new SessionManager();
