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

/**
 * 管理员信息 Store
 *
 * - token / adminInfo 通过 pinia-plugin-persistedstate 持久化到 localStorage（key: snack-admin-user）
 * - 刷新页面后会自动从持久化数据恢复登录态
 * - 401 由 request 拦截器统一处理：清空登录态 + 跳 /login
 */
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>('')
    const adminInfo = ref<AdminInfo | null>(null)

    const isLoggedIn = computed(() => !!token.value)
    const username = computed(() => adminInfo.value?.username ?? '')
    const nickname = computed(() => adminInfo.value?.nickname ?? '')
    const avatar = computed(() => adminInfo.value?.avatar ?? '')
    const role = computed(() => adminInfo.value?.role ?? '')

    /**
     * 登录
     * 后端 LoginVO 已包含 adminInfo，因此同步写入；不必再额外调 /info
     */
    async function login(params: LoginParams): Promise<LoginResult> {
      const data = await loginApi(params)
      token.value = data.token
      if (data.adminInfo) {
        adminInfo.value = data.adminInfo
      }
      return data
    }

    /**
     * 拉取当前登录管理员信息（用于刷新页面 / token 仍有效但 adminInfo 丢失的场景）
     */
    async function fetchAdminInfo(): Promise<AdminInfo> {
      const data = await getAdminInfoApi()
      adminInfo.value = data
      return data
    }

    async function logout(): Promise<void> {
      try {
        await logoutApi()
      } catch {
        /* 即便后端登出失败，前端也要清掉本地登录态 */
      } finally {
        clearAuth()
      }
    }

    function clearAuth(): void {
      token.value = ''
      adminInfo.value = null
    }

    return {
      token,
      adminInfo,
      isLoggedIn,
      username,
      nickname,
      avatar,
      role,
      login,
      logout,
      fetchAdminInfo,
      clearAuth
    }
  },
  {
    persist: {
      key: 'snack-admin-user',
      pick: ['token', 'adminInfo']
    }
  }
)
