import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api, setApiToken } from '@/tools/web.ts'
import type { UserDto } from '@/types/user.ts'

export const useNowUser = defineStore('now-user', () => {
  const isLogin = ref(false)

  const id = ref(0)
  const name = ref('')
  const display_name = ref('')
  const email = ref('')
  const phone = ref('')
  const avatar_url = ref('')
  const background_url = ref('')
  const description = ref('')
  const is_admin = ref(false)

  async function loadUserInfo(user_id: number, access_token: string) {
    id.value = user_id
    setApiToken(access_token)

    let user: UserDto
    try {
      user = await api.get('/admin/me/').then((res) => res.data as UserDto)
    } catch (err) {
      console.error(`请求用户信息时失败：${err}`)
      throw err
    }

    await loadWithUserInfo(user)
  }

  async function loadWithUserInfo(user: UserDto) {
    name.value = user.name
    display_name.value = user.display_name
    email.value = user.email
    phone.value = user.phone
    avatar_url.value = user.avatar_url
    background_url.value = user.background_url
    description.value = user.description
    is_admin.value = user.is_admin

    isLogin.value = true
  }

  return {
    isLogin,
    id,
    name,
    display_name,
    email,
    phone,
    avatar_url,
    background_url,
    description,
    is_admin,
    loadUserInfo,
    loadWithUserInfo,
  }
})
