import { createContext, useContext, useEffect, useState } from 'react'; import { User, Session } from '@supabase/supabase-js'; import { supabase } from '@/integrations/supabase/client'; import { Profile } from '@/types/database'; interface AuthContextType { user: User | null; session: Session | null; profile: Profile | null; loading: boolean; signOut: () => Promise; refreshProfile: () => Promise; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [session, setSession] = useState(null); const [profile, setProfile] = useState(null); const [loading, setLoading] = useState(true); const fetchProfile = async (userId: string) => { try { const { data, error } = await supabase .from('profiles') .select(`*, location:locations(*)`) .eq('user_id', userId) .maybeSingle(); if (error && error.code !== 'PGRST116') { console.error('Error fetching profile:', error); return; } setProfile(data as Profile); } catch (error) { console.error('Error fetching profile:', error); } }; const refreshProfile = async () => { if (user) { await fetchProfile(user.id); } }; useEffect(() => { // Get initial session supabase.auth.getSession().then(({ data: { session } }) => { setSession(session); setUser(session?.user ?? null); if (session?.user) { fetchProfile(session.user.id); } setLoading(false); }); // Listen for auth changes const { data: { subscription }, } = supabase.auth.onAuthStateChange(async (event, session) => { setSession(session); setUser(session?.user ?? null); if (session?.user) { await fetchProfile(session.user.id); } else { setProfile(null); } setLoading(false); }); return () => subscription.unsubscribe(); }, []); const signOut = async () => { const { error } = await supabase.auth.signOut(); if (error) { console.error('Error signing out:', error); throw error; } }; const value = { user, session, profile, loading, signOut, refreshProfile, }; return {children}; } export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }