import AsyncStorage from "@react-native-async-storage/async-storage";
import {
  getReactNativePersistence,
  initializeAuth,
} from "firebase/auth/react-native";
import firebase from "firebase/compat/app";

import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";

export const firebaseConfig = {
  apiKey: "AIzaSyCuHJHdwVN_F-VmUG4Hd7bGiMRqj6rPlLo",
  authDomain: "musicland-d33f9.firebaseapp.com",
  projectId: "musicland-d33f9",
  storageBucket: "musicland-d33f9.firebasestorage.app",
  messagingSenderId: "305598753437",
  appId: "1:305598753437:web:9930f10af59e5cf7f28274",
  measurementId: "G-RV4MS1SVTT",
};

if (!firebase?.apps?.filter(({ name_ }) => name_ === "[DEFAULT]").length) {
  const defaultApp = firebase.initializeApp(firebaseConfig);

  initializeAuth(defaultApp, {
    persistence: getReactNativePersistence(AsyncStorage),
  });

  // if (__DEV__) {
  //   firebase.functions().useEmulator("localhost", 5001);
  // }
  console.log("Firebase init");
}

// Firestore settings for React Native/iOS: avoid streaming transport issues
const firestore = firebase.firestore();
try {
  // Prefer auto-detect; disable fetch streams for RN iOS stability
  firebase.firestore().settings({
    experimentalAutoDetectLongPolling: true,
    useFetchStreams: false,
    ignoreUndefinedProperties: true,
  });
} catch (e) {
  // Ignore if settings were already set elsewhere
}

export const usersRef = firestore.collection("users");
export const projectsRef = firestore.collection("projects");
export const playlistsRef = firestore.collection("playlists");
export const chatsRef = firestore.collection("chats");

export const { arrayUnion, arrayRemove, increment, serverTimestamp } =
  firebase.firestore.FieldValue;

export default firebase;
