/**
 * @deprecated This context has been removed in Phase 4 migration.
 * All session state is now managed in Redux activeSessionSlice.
 *
 * Migration Guide:
 * - Replace useCurrentSessionContext() with Redux selectors:
 *   - currentSession → useSelector(selectActiveSession)
 *   - sessionId → useSelector(selectSessionId)
 *   - inSession() → useSelector(selectInSession)
 * - Replace setCurrentSessionId(id) → dispatch(setSessionId(id))
 * - Replace setCurrentSession(data) → dispatch(updateSessionData(data))
 *
 * See: src/store/features/activeSessionSlice.js
 * Documentation: docs/PHASE4_MIGRATION_SUMMARY.md
 */

import React, { createContext, useContext, useState, useRef, useEffect } from 'react';
import { useJamServerContext } from './JamServerContext';
import { getSessionHistory } from '../helpers/rest';

const CurrentSessionContext = createContext(null);

export const CurrentSessionProvider = ({ children }) => {
  const [currentSession, setCurrentSession] = useState({});
  const currentSessionIdRef = useRef(null);

  const inSession = () => {
    return currentSessionIdRef.current !== null;
  };

  const setCurrentSessionId = (id) => {
    console.log("Setting current session ID to: ", id);
    currentSessionIdRef.current = id;
  };

  const refreshSession = async () => {
    if (currentSessionIdRef.current) {
      try {
        const sessionData = await getSessionHistory(currentSessionIdRef.current);
        const musicSession = await sessionData.json();
        setCurrentSession(musicSession);
      } catch (error) {
        console.error("Failed to refresh session data:", error);
      }
    }else {
      console.warn("No current session ID set; cannot refresh session data.");
    }
  };

  return (
    <CurrentSessionContext.Provider value={{
      currentSession,
      setCurrentSession,
      inSession,
      setCurrentSessionId,
      currentSessionIdRef,
    }}
    >
      {children}
    </CurrentSessionContext.Provider>
  );
};

export const useCurrentSessionContext = () => useContext(CurrentSessionContext);
