import React, { createContext, useContext, useEffect, useState } from "react"; import { Tunables } from '../../Components/ChatQuery'; import { SetSnackType } from '../../Components/Snack'; import { connectionBase } from '../../Global'; // Define the UserInfo interface for type safety interface UserQuestion { question: string; tunables?: Tunables; }; interface UserInfo { type: 'candidate' | 'employer' | 'guest'; description: string; rag_content_size: number; username: string; first_name: string; last_name: string; full_name: string; contact_info: Record; questions: UserQuestion[], isAuthenticated: boolean, has_profile: boolean, title: string; location: string; email: string; phone: string; // Fields used in AI generated personas age?: number, ethnicity?: string, gender?: string, }; type UserContextType = { user: UserInfo | null; setUser: (user: UserInfo | null) => void; }; const UserContext = createContext(undefined); const useUser = () => { const ctx = useContext(UserContext); if (!ctx) throw new Error("useUser must be used within a UserProvider"); return ctx; }; interface UserProviderProps { children: React.ReactNode; sessionId: string | undefined; setSnack: SetSnackType; }; const UserProvider: React.FC = (props: UserProviderProps) => { const { sessionId, children, setSnack } = props; const [user, setUser] = useState(null); useEffect(() => { if (!sessionId || user) { return; } const fetchUserFromSession = async (): Promise => { try { let response; response = await fetch(`${connectionBase}/api/user/${sessionId}`, { method: 'GET', credentials: 'include', }); if (!response.ok) { throw new Error('Session not found'); } const user: UserInfo = { ...(await response.json()), type: "guest", isAuthenticated: false, logout: () => { }, } console.log("Loaded user:", user); setUser(user); } catch (err) { setSnack("" + err); setUser(null); } return null; }; fetchUserFromSession(); }, [sessionId, user, setUser]); if (sessionId === undefined) { return <>; } return ( {children} ); }; export type { UserInfo }; export { UserProvider, useUser };