import { create } from 'zustand'; import api from '../api/axiosConfig'; const useAuthStore = create((set) => ({ isAuthenticated: false, isLoading: true, error: null, user: null, login: async (username, password) => { set({ isLoading: true, error: null }); try { const res = await api.post('login/', { username, password }); set({ isAuthenticated: true, isLoading: false, user: { username: res.data.username, firstName: res.data.first_name, lastName: res.data.last_name, email: res.data.email, fullName: [res.data.first_name, res.data.last_name].filter(Boolean).join(' '), // Catch the layout and map data on fresh login! preferences: res.data.preferences || {} } }); } catch (err) { // PROPER USAGE: Check if Django sent a specific error string, otherwise default const backendError = err.response?.data?.error || 'Invalid network credentials'; set({ error: backendError, isLoading: false, isAuthenticated: false }); } }, logout: async () => { try { await api.post('logout/'); } catch (err) { console.error("Logout error:", err); } finally { set({ isAuthenticated: false, user: null, error: null }); } }, checkAuth: async () => { try { // Hit the new lightweight endpoint const res = await api.get('session/'); // Rehydrate the store with the user's info! set({ isAuthenticated: true, isLoading: false, user: { username: res.data.username, firstName: res.data.first_name, lastName: res.data.last_name, email: res.data.email, fullName: [res.data.first_name, res.data.last_name].filter(Boolean).join(' '), // Catch the layout and map data on page refresh! preferences: res.data.preferences || {} } }); } catch { // If it fails, ensure the store is completely wiped set({ isAuthenticated: false, isLoading: false, user: null }); } }, // Allow the UI to save widget placement saveDashboardLayout: async (newLayout) => { try { // 1. Optimistically update React state for zero UI lag set((state) => ({ user: { ...state.user, preferences: { ...state.user.preferences, dashboard_layout: newLayout } } })); // 2. Quietly push the save command to Django await api.post('dashboard/save/', { layout: newLayout }); } catch (error) { console.error("Failed to save layout to database", error); } }, // updateProfile: async (newProfile) => { // try { // set((state) => ({ // user: { // ...state.user, // username: newProfile.username, // } // })); // // await api.post('profile/update/', { profile: newProfile }); // } catch (error) { // console.error("Failed to update profile", error); // } // } })); export default useAuthStore;