"use client"; import React, { createContext, useContext, useEffect, useState } from "react"; import { onAuthStateChanged, User as FirebaseUser, signOut } from "firebase/auth"; import { ref, get, update } from "firebase/database"; import { auth, db } from "@/lib/firebase"; import { RestaurantUser } from "@/types/user"; import { useRouter } from "next/navigation"; interface AuthContextType { user: RestaurantUser | null; firebaseUser: FirebaseUser | null; loading: boolean; logout: () => Promise; updateRestaurantProfile: (updates: Partial) => Promise<{ success: boolean; error?: any }>; } const AuthContext = createContext({ user: null, firebaseUser: null, loading: true, logout: async () => {}, updateRestaurantProfile: async () => ({ success: false }), }); export const AuthProvider = ({ children }: { children: React.ReactNode }) => { const router = useRouter(); const [user, setUser] = useState(null); const [firebaseUser, setFirebaseUser] = useState(null); const [loading, setLoading] = useState(true); const buildDocumentId = (email: string) => { return email.replace(/\./g, "_").replace(/@/g, "_at_"); }; useEffect(() => { const unsubscribe = onAuthStateChanged(auth, async (currentUser) => { try { if (currentUser && currentUser.email) { setFirebaseUser(currentUser); const docId = buildDocumentId(currentUser.email); const userRef = ref(db, `Restaurantes/${docId}`); const snapshot = await get(userRef); if (snapshot.exists()) { const data = snapshot.val() as RestaurantUser; if (data.accountType === "ESTABELECIMENTO") { setUser(data); } else { console.warn("User is not a restaurant"); setUser(null); await signOut(auth); } } else { console.warn("User record not found in Restaurantes"); setUser(null); } } else { setFirebaseUser(null); setUser(null); } } catch (error) { console.error("Auth initialization error:", error); } finally { setLoading(false); } }); return () => unsubscribe(); }, []); const logout = async () => { try { await signOut(auth); router.push("/login"); } catch (error) { console.error("Erro ao fazer logout:", error); } }; const updateRestaurantProfile = async (updates: Partial) => { if (!firebaseUser?.email) return { success: false, error: "Utilizador não autenticado" }; try { const docId = buildDocumentId(firebaseUser.email); const userRef = ref(db, `Restaurantes/${docId}`); await update(userRef, updates); setUser(prev => prev ? { ...prev, ...updates } : null); return { success: true }; } catch (error) { console.error("Erro ao atualizar perfil:", error); return { success: false, error }; } }; return ( {children} ); }; export const useAuth = () => useContext(AuthContext);