import { defineStore } from 'pinia'
import type { UserInfo, UserState } from './helper'
import { defaultSetting, getLocalState, setLocalState } from './helper'
import { fetchMy } from '@/api'
import { useAuthStore } from '../auth'
import { useUserMemberStore } from '../memberShip'

export const useUserStore = defineStore('user-store', {
    state: (): UserState => defaultSetting(),
    actions: {
        setUserInfo(userInfo: Partial<UserInfo>) {
            this.userInfo = { ...this.userInfo, ...userInfo }
            this.recordState()
        },

        resetUserInfo() {
            this.userInfo = { ...defaultSetting().userInfo }
            this.recordState()
        },

        recordState() {
            setLocalState(this.$state)
        },

        async fetch() {
            const data = await fetchMy<UserInfo>()
            this.setUserInfo(data)
            await useUserMemberStore().fetchMember()
        },

        logout() {
            this.resetUserInfo()
            useAuthStore().removeToken()
        }
    }
})
