import { useState, useCallback, useEffect } from 'react'; import api from '../utils/api'; import { useAuth } from './useAuth'; export interface User { id: string; email: string; full_name: string; role: string; team?: string; is_active: boolean; avatar_url?: string; } // Global singleton for user list with hydration const USERS_CACHE_KEY = 'nexus_users_v1'; let globalUsers: User[] = (() => { try { const cached = sessionStorage.getItem(USERS_CACHE_KEY); return cached ? JSON.parse(cached) : []; } catch { return []; } })(); let globalUsersLoading = false; let globalUsersError: string | null = null; let globalUsersLoaded = false; let lastLoadedWorkspaceId: string | undefined = undefined; const usersListeners = new Set<(u: User[], l: boolean, e: string | null, d: boolean) => void>(); const notifyUsers = () => usersListeners.forEach(l => l(globalUsers, globalUsersLoading, globalUsersError, globalUsersLoaded)); export const useUsers = (workspaceId?: string) => { const [localUsers, setLocalUsers] = useState(globalUsers); const [loading, setLoading] = useState(globalUsersLoading); const [error, setError] = useState(globalUsersError); const [loaded, setLoaded] = useState(globalUsersLoaded); useEffect(() => { const listener = (u: User[], l: boolean, e: string | null, d: boolean) => { setLocalUsers(u); setLoading(l); setError(e); setLoaded(d); }; usersListeners.add(listener); return () => { usersListeners.delete(listener); }; }, []); const fetchUsers = useCallback(async (force: boolean = false) => { const isNewWorkspace = lastLoadedWorkspaceId !== workspaceId; if (!force && globalUsers.length > 0 && !isNewWorkspace) return; lastLoadedWorkspaceId = workspaceId; globalUsersLoading = true; notifyUsers(); try { let url = workspaceId ? `users/?workspace_id=${workspaceId}` : 'users/'; if (force) { url += (url.includes('?') ? '&' : '?') + 'bypass_cache=true'; } const response = await api.get(url); globalUsers = response.data; sessionStorage.setItem(USERS_CACHE_KEY, JSON.stringify(globalUsers)); globalUsersError = null; globalUsersLoaded = true; } catch (err: any) { globalUsersError = err.response?.data?.detail || 'Failed to fetch users'; } finally { globalUsersLoading = false; notifyUsers(); } }, [workspaceId]); const addUser = async (payload: any) => { try { // Inject workspace context if hook is scoped const finalPayload = { ...payload }; if (workspaceId && !finalPayload.workspace_id) { finalPayload.workspace_id = workspaceId; } console.log('🚀 Provisioning User:', finalPayload); const response = await api.post('users/', finalPayload); await fetchUsers(true); return response.data; } catch (err: any) { const detail = err.response?.data?.detail; const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail; throw new Error(msg || 'Failed to add user'); } }; const { token } = useAuth(); useEffect(() => { if (token) { fetchUsers(); } }, [fetchUsers, token]); const updateUser = async (userId: string, payload: any) => { try { const response = await api.patch(`users/${userId}/`, payload); await fetchUsers(true); return response.data; } catch (err: any) { const detail = err.response?.data?.detail; const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail; throw new Error(msg || 'Failed to update user'); } }; const deleteUser = async (userId: string) => { try { await api.delete(`users/${userId}/`); await fetchUsers(true); } catch (err: any) { const detail = err.response?.data?.detail; const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail; throw new Error(msg || 'Failed to delete user'); } }; return { users: localUsers, loading, error, loaded, refresh: () => fetchUsers(true), addUser, updateUser, deleteUser }; };