// src/storage/index.js — storage factory + SDK re-exports.
// STORAGE=firebase (default): adapter wraps SDK. STORAGE=ws: backend.
// App.js imports getStorage() for subscribe; still imports SDK pieces for writes (per-group refactor pending).

import { initializeApp } from 'firebase/app';
import {
  getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken,
} from 'firebase/auth';
import {
  getFirestore, doc, setDoc, getDoc, getDocs, addDoc, collection,
  onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch,
} from 'firebase/firestore';
import { initFirebase, createFirebaseStorage } from './firebase';
import { createWsStorage } from './ws';
import { createMemoryStorage } from './memory';

let storageInstance = null;

// Returns adapter instance implementing interface (getDoc/setDoc/subscribeDoc/etc).
export function getStorage() {
  if (storageInstance) return storageInstance;
  const mode = process.env.REACT_APP_STORAGE || 'firebase';
  if (mode === 'firebase') {
    const ok = initFirebase();
    if (!ok) throw new Error('Firebase config missing. Check REACT_APP_FIREBASE_* env.');
    storageInstance = createFirebaseStorage();
  } else if (mode === 'ws') {
    storageInstance = createWsStorage({
      baseUrl: process.env.REACT_APP_BACKEND_URL || '',
      wsUrl: process.env.REACT_APP_BACKEND_WS || '',
    });
  } else {
    storageInstance = createMemoryStorage();
  }
  return storageInstance;
}

export function getStorageMode() {
  return process.env.REACT_APP_STORAGE || 'firebase';
}

export {
  initializeApp,
  getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken,
  getFirestore, doc, setDoc, getDoc, getDocs, addDoc, collection,
  onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch,
};
