// stores/authStore.js
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

export const useAuthStore = create(
    persist(
        (set) => ({
            user: null,
            token: null,
            isAuthenticated: false,

            // Actions
            login: (userData, token) => set({
                user: {
                    id: userData.id,
                    email: userData.email,
                    name: userData.name,
                    role: userData.role,
                    profile: userData.profile
                },
                token,
                isAuthenticated: true,
            }),

            logout: () => set({
                user: null,
                token: null,
                isAuthenticated: false
            }),

            setUser: (userData) => set({
                user: { ...userData },
                isAuthenticated: !!userData
            }),
        }),
        {
            name: 'auth-storage', // LocalStorage key
            storage: createJSONStorage(() => localStorage),
            partialize: (state) => ({
                user: state.user,
                token: state.token,
                isAuthenticated: state.isAuthenticated
            })
        }
    )
);