import { ref, computed } from 'vue'; import { signInWithPopup, signOut as firebaseSignOut, onAuthStateChanged, User, AuthError } from 'firebase/auth'; import { getFirebaseAuth, getAuthProvider } from '../utils/firebase'; // Global state (Singleton pattern for composable) const currentUser = ref(null); const isLoading = ref(true); let isListenerAttached = false; /** * Composable for Firebase Authentication. * Provides reactive user state and login/logout methods. */ export function useAuth() { /** * Helper to safely get auth instance or throw. */ const ensureAuth = () => { try { return { auth: getFirebaseAuth(), provider: getAuthProvider() }; } catch (e) { throw new Error("Authentication service is not ready. Ensure initFirebase() is called in main.ts"); } }; const loginWithGoogle = async (): Promise => { const { auth, provider } = ensureAuth(); try { const result = await signInWithPopup(auth, provider); currentUser.value = result.user; return result.user; } catch (error: unknown) { const authError = error as AuthError; console.error(`[Auth] Login failed: ${authError.code} - ${authError.message}`); throw authError; // Propagate for UI handling } }; const logout = async (): Promise => { try { const auth = getFirebaseAuth(); // Can just get auth, provider not needed await firebaseSignOut(auth); currentUser.value = null; } catch (error: unknown) { console.error("[Auth] Logout failed", error); throw error; } }; /** * Initialize the Auth listener. * Idempotent: calling it multiple times is safe. */ const initAuthListener = (): void => { if (isListenerAttached) return; try { const auth = getFirebaseAuth(); onAuthStateChanged(auth, (user) => { currentUser.value = user; isLoading.value = false; }); isListenerAttached = true; } catch (e) { // If firebase isn't ready yet, this might fail. // In a strict app, this shouldn't happen if main.ts inits first. console.warn("[Auth] Failed to attach listener:", e); } }; return { user: computed(() => currentUser.value), isAuthenticated: computed(() => !!currentUser.value), isLoading: computed(() => isLoading.value), loginWithGoogle, logout, initAuthListener }; }