import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginApi } from '@/api/auth'
import type { LoginParams, LoginResult } from '@/types/auth'

/**
 * 用户 Store
 *
 * - token 通过 pinia-plugin-persistedstate 持久化到 localStorage（key: snack-user）
 * - 刷新页面后自动恢复登录态
 * - 401 由 request 拦截器统一处理：清空登录态 + 跳 /login
 */
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>('')
    const userId = ref<number>(0)
    const nickname = ref<string>('')

    const isLoggedIn = computed(() => !!token.value)
    const displayName = computed(() => nickname.value || '用户')

    /** 登录 */
    async function login(params: LoginParams): Promise<LoginResult> {
      const data = await loginApi(params)
      token.value = data.token
      userId.value = data.userId
      nickname.value = data.nickname
      return data
    }

    /** 登出 */
    function logout(): void {
      clearAuth()
    }

    function clearAuth(): void {
      token.value = ''
      userId.value = 0
      nickname.value = ''
    }

    return {
      token,
      userId,
      nickname,
      isLoggedIn,
      displayName,
      login,
      logout,
      clearAuth
    }
  },
  {
    persist: {
      key: 'snack-user',
      pick: ['token', 'userId', 'nickname']
    }
  }
)
