// src/services/websocket.js

import { createSession } from "./apiService";

/**
 * Gets a session ID from localStorage or creates a new one via the API.
 * @param {string} featureNamespace - The key suffix to use for isolated storage.
 * @returns {Promise<string>} The session ID.
 */
export const getSessionId = async (featureNamespace = "default", providerName = "deepseek", extraParams = {}) => {
  const storageKey = featureNamespace === "default" ? "sessionId" : `sessionId_${featureNamespace}`;
  let sessionId = localStorage.getItem(storageKey);
  if (!sessionId) {
    // No existing session, so create one via API
    const session = await createSession(featureNamespace, providerName, extraParams);
    sessionId = session.id;

    // Store it in localStorage for reuse
    localStorage.setItem(storageKey, sessionId);
  } else {
    // Verify it still exists remotely (wasn't deleted on another device or tab)
    try {
      const { getSession } = require("./apiService");
      await getSession(sessionId);
    } catch (e) {
      console.warn("Session in localStorage was invalid or deleted, creating a new one...", e);
      const session = await createSession(featureNamespace, providerName, extraParams);
      sessionId = session.id;
      localStorage.setItem(storageKey, sessionId);
    }
  }

  console.log(`Using session ID for [${featureNamespace}]:`, sessionId);
  return sessionId;
};
