import {
  fetchUser,
  fetchUserMeta,
  postLogin,
  postLogout,
  setToken,
  delToken
} from '@/api'
import { defineStore } from 'pinia'

import type { User, UserMeta, LoginState } from '@/api'

const defState = {
  current: {
    nickname: '游客',
    phone: '',
    email: '',
    avatar: 'https://4dkk.4dage.com/head/18819272208/head_1662022947583.png'
  } as User,
  meta: {
    projectCount: 0,
    projectFileCount: 0,
    projectSceneCount: 0,
    projectOverCount: 0
  } as UserMeta
}

export const useUserStore = defineStore('user', {
  state: () => defState,
  actions: {
    async fetchUser() {
      this.current = await fetchUser()
    },
    async fetchMeta() {
      this.meta = await fetchUserMeta()
      console.log(this.$state)
    },
    fetch() {
      return Promise.all([this.fetchUser(), this.fetchMeta()])
    },
    async login(state: LoginState) {
      const { token, user } = await postLogin({
        phone: state.phone,
        password: state.password
      })
      this.current = user
      setToken(token)
    },
    async logout() {
      await postLogout()
      this.$state = defState
      delToken()
    }
  }
})
