import { defineStore } from 'pinia'

import { LoginReq, SysUser } from '@/types/api/auth'
import { loginApi } from '@/api/auth'
import { setToken } from '@/api/axios'
import router from '@/router'

export interface AppStoreState {
  user?: SysUser
  token?: string
}
const useUserStore = defineStore('user', {
  state: () => {
    let user: SysUser | undefined
    const userJson = localStorage.getItem('user')
    if (userJson) {
      try {
        user = JSON.parse(userJson)
      } catch {
        // ignore
      }
    }
    return { user } as AppStoreState
  },
  actions: {
    setUser(user?: SysUser) {
      this.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    async login(data: LoginReq) {
      try {
        const resp = await loginApi(data)
        this.setUser(resp.data.sysUser)
        setToken(resp.data.token)
        router.push({ path: '/dashboard' })
      } catch (error) {
        // showError(error)
      }
    },
    async logout() {
      this.setUser(undefined)
      setToken('')
    },
  },
})

export default useUserStore
