import { create } from 'zustand'; import { api, ApiError } from '@/lib/api'; interface User { id: string; email: string; username: string; isSuperAdmin: boolean; avatarUrl: string | null; } interface AuthState { user: User | null; isLoading: boolean; isAuthenticated: boolean; login: (email: string, password: string) => Promise; register: (email: string, username: string, password: string) => Promise; logout: () => Promise; fetchUser: () => Promise; } export const useAuthStore = create((set) => ({ user: null, isLoading: true, isAuthenticated: false, login: async (email, password) => { const data = await api.post<{ accessToken: string; user: User }>('/auth/login', { email, password, }); localStorage.setItem('access_token', data.accessToken); set({ user: data.user, isAuthenticated: true }); }, register: async (email, username, password) => { const data = await api.post<{ accessToken: string; user: User }>('/auth/register', { email, username, password, }); localStorage.setItem('access_token', data.accessToken); set({ user: data.user, isAuthenticated: true }); }, logout: async () => { try { await api.post('/auth/logout'); } catch { // ignore } localStorage.removeItem('access_token'); set({ user: null, isAuthenticated: false }); }, fetchUser: async () => { try { const data = await api.get<{ user: User }>('/auth/me'); set({ user: data.user, isAuthenticated: true, isLoading: false }); } catch (err) { if (err instanceof ApiError && err.status === 401) { set({ user: null, isAuthenticated: false, isLoading: false }); } else { set({ isLoading: false }); } } }, }));