
export const useUserStore = defineStore('user', {
    state: () => {
        return {
            id: null,
            profile: {}
        }
    },
    actions: {
        async register(body) {
            body.password = this.profile.password
            const method = 'post'
            const result = await useFetch(`/api/users/register`, { method, body })

            if (result.status.value == 'success') {
                this.id = result.data.value._id
                this.setToken(result.data.value)
            }

            return result;
        },
        async login(form) {
            const isEmail = form.username?.includes('@')
            const type = isEmail ? 'email' : 'number'
            const key = isEmail ? 'email' : 'phoneNumber'

            const body = {
                [key]: form.username,
                password: form.password,
                remember: form.remember
            }

            const method = 'post'
            const result = await useFetch(`/api/users/login/${type}`, { method, body })

            if (result.status.value == 'success') {
                this.id = result.data.value._id
                this.setToken(result.data.value)
            }

            return result;
        },
        async get() {
            const { status, data, error } = await useFetch('/api/users/current', {
                headers: {
                    Authorization: useCookie('token')
                }
            })

            if (status.value == 'success') {
                this.id = data.value._id
                this.profile = data.value
                const favorites = useFavoritesStore()
                favorites.items = data.value.favoriteProducts

                const cart = useCartStore()
                cart.get()
            }
        },
        async forgetPassword(form) {
            const result = await useFetch('/api/users/forgot', {
                method: 'post', body: form
            })

            return result;
        },
        setToken(data) {
            const token = useCookie('token', { expires: new Date(data.expiredDate) })
        
            token.value = data.accessToken
            document.cookie
        }
    }
})
