import AsyncStorage from '@react-native-async-storage/async-storage';
import { getApps, initializeApp } from 'firebase/app';
import { connectAuthEmulator, getAuth, type Auth } from 'firebase/auth';
import { connectFirestoreEmulator, getFirestore } from 'firebase/firestore';
import { connectFunctionsEmulator, getFunctions } from 'firebase/functions';
import { Platform } from 'react-native';
import type { FirebaseApp } from 'firebase/app';

type ReactNativeAuthModule = {
  getAuth(app?: FirebaseApp): Auth;
  initializeAuth(
    app: FirebaseApp,
    deps?: { persistence?: unknown }
  ): Auth;
  getReactNativePersistence(storage: typeof AsyncStorage): unknown;
};

const firebaseConfig = {
  apiKey:
    process.env.EXPO_PUBLIC_FIREBASE_API_KEY,
  authDomain:
    process.env.EXPO_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId:
    process.env.EXPO_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket:
    process.env.EXPO_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId:
    process.env.EXPO_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.EXPO_PUBLIC_FIREBASE_APP_ID,
};

const isAppInitialized = getApps().length > 0;
const app = isAppInitialized ? getApps()[0] : initializeApp(firebaseConfig);
const useFirebaseEmulators = true;
const firebaseEmulatorHost = '192.168.1.127';
const reactNativeAuth =
  Platform.OS === 'web'
    ? null
    : (require('@firebase/auth') as ReactNativeAuthModule);

const auth =
  Platform.OS === 'web'
    ? getAuth(app)
    : isAppInitialized
      ? (reactNativeAuth as ReactNativeAuthModule).getAuth(app)
      : (reactNativeAuth as ReactNativeAuthModule).initializeAuth(app, {
          persistence: (reactNativeAuth as ReactNativeAuthModule).getReactNativePersistence(AsyncStorage),
        });

const db = getFirestore(app);
const functions = getFunctions(app);

if (useFirebaseEmulators ) {
  console.info(
    `[firebase] using local emulators on ${firebaseEmulatorHost} (auth:9099, firestore:8080, functions:5001)`
  );
  // connectAuthEmulator(auth, `http://${firebaseEmulatorHost}:9099`, {
  //   disableWarnings: true,
  // });
  // connectFirestoreEmulator(db, firebaseEmulatorHost, 8080);
  connectFunctionsEmulator(functions, firebaseEmulatorHost, 5001);
} else {
  console.info('[firebase] using production Firebase services');
}

export { auth, db, functions };
