File size: 2,778 Bytes
35765b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import type { User } from '../types';
import { api } from '../api/client';

interface UserContextType {
  user: User | null;
  isLoading: boolean;
  error: string | null;
  login: (firstName: string, lastName: string) => Promise<void>;
  loginWithId: (userId: string) => Promise<void>;
  logout: () => void;
}

const UserContext = createContext<UserContextType | null>(null);

const USER_STORAGE_KEY = 'project_memory_user';

export function UserProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Check for stored user on mount
  useEffect(() => {
    const stored = localStorage.getItem(USER_STORAGE_KEY);
    if (stored) {
      try {
        const userData = JSON.parse(stored) as User;
        // Verify user still exists in backend
        api.getUser(userData.id)
          .then(user => {
            setUser(user);
            setIsLoading(false);
          })
          .catch(() => {
            // User no longer exists, clear storage
            localStorage.removeItem(USER_STORAGE_KEY);
            setIsLoading(false);
          });
      } catch {
        localStorage.removeItem(USER_STORAGE_KEY);
        setIsLoading(false);
      }
    } else {
      setIsLoading(false);
    }
  }, []);

  const login = async (firstName: string, lastName: string) => {
    setIsLoading(true);
    setError(null);
    try {
      const newUser = await api.createUser({ firstName, lastName });
      setUser(newUser);
      localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(newUser));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create user');
      throw err;
    } finally {
      setIsLoading(false);
    }
  };

  const loginWithId = async (userId: string) => {
    setIsLoading(true);
    setError(null);
    try {
      const existingUser = await api.getUser(userId);
      setUser(existingUser);
      localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(existingUser));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'User not found');
      throw err;
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem(USER_STORAGE_KEY);
  };

  return (
    <UserContext.Provider value={{ user, isLoading, error, login, loginWithId, logout }}>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
}