// src/storage/index.js — storage factory + SDK re-exports.
// STORAGE=firebase (default): adapter wraps SDK. STORAGE=server: backend.
// orderBy/limit below = NEUTRAL builders (not SDK passthrough).
// 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, writeBatch,
} from 'firebase/firestore';
import { initFirebase, createFirebaseStorage } from './firebase';
import { createServerStorage } from './server';

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 === 'server') {
    storageInstance = createServerStorage({
      baseUrl: process.env.REACT_APP_BACKEND_URL || '',
      realtimeUrl: process.env.REACT_APP_BACKEND_REALTIME_URL || '',
    });
  } else {
    throw new Error(`Unknown REACT_APP_STORAGE mode: ${mode}. Use 'firebase' or 'server'.`);
  }
  return storageInstance;
}

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

// Neutral query-constraint builders. App builds constraints with these (not
// raw SDK), so both adapters read the same shape. firebase adapter translates
// neutral -> SDK; server adapter applies client-side. Combat log uses these:
//   [orderBy('timestamp','desc'), limit(500)]
export function where(field, op, value) { return { __type: 'where', field, op, value }; }
export function orderBy(field, dir) { return { __type: 'orderBy', field, dir }; }
export function limit(n) { return { __type: 'limit', n }; }
export function offset(n) { return { __type: 'offset', offset: n }; }

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