import { defineStore } from 'pinia'
import { ss } from '@/utils/storage'
import { type UserState, type UserInfo, UserStoreStorageKeyEnum } from '../types/user'
import { fetchUserDetailInfo } from '@/apis/user'

export function createDefaultUserInfoFactory(): UserInfo {
  return {
    memberId: null,
    avatarUrl: '',
    nickName: '',
    mobilePhone: '',
    remark: '',
    email: '',
  }
}

export const useUserStore = defineStore('user-store', {
  state: (): UserState => ({
    isLogin: ss.get(UserStoreStorageKeyEnum.isLogin),
    token: ss.get(UserStoreStorageKeyEnum.token) || '',
    userInfo: ss.get(UserStoreStorageKeyEnum.userInfo) || createDefaultUserInfoFactory(),
  }),
  actions: {
    async logout() {
      this.isLogin = false
      this.token = ''
      this.userInfo = createDefaultUserInfoFactory()

      ss.remove(UserStoreStorageKeyEnum.isLogin)
      ss.remove(UserStoreStorageKeyEnum.token)
      ss.remove(UserStoreStorageKeyEnum.userInfo)
    },
    updateToken(token: string) {
      this.token = token
      ss.set(UserStoreStorageKeyEnum.token, token)

      if (token) {
        this.isLogin = true
        ss.set(UserStoreStorageKeyEnum.isLogin, true)
      } else {
        this.isLogin = false
        ss.set(UserStoreStorageKeyEnum.isLogin, false)
      }
    },
    updateUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      ss.set(UserStoreStorageKeyEnum.userInfo, userInfo)
    },
    fetchUpdateUserInfo() {
      fetchUserDetailInfo<UserInfo>().then((res) => {
        this.userInfo = res.data
      })
    },
  },
})
