import { computed, ref } from 'vue'
import { getDashboard, type DashboardSnapshot } from '@/api/dashboard'
import { getAuthToken } from '@/api/request'

const value = ref<DashboardSnapshot | null>(null)
const token = ref<string | null>(null)
const error = ref('')
const loadedAt = ref<number | null>(null)
let pending: { token: string | null; promise: Promise<void> } | undefined
const snapshot = computed(() => token.value === getAuthToken() ? value.value : null)
/** 首页与顶部概览使用同一响应，会话切换时清除旧账号可见的数据。 */
export function clearDashboard() { value.value = null; token.value = null; loadedAt.value = null; error.value = ''; pending = undefined }
export function useDashboard() {
  function load(): Promise<void> {
    const current = getAuthToken()
    if (pending?.token === current) return pending.promise
    if (token.value !== current) { value.value = null; loadedAt.value = null }
    token.value = current; error.value = ''
    const request = { token: current, promise: Promise.resolve() }
    request.promise = getDashboard().then(result => {
      if (pending === request && current === getAuthToken()) { value.value = result; loadedAt.value = Date.now() }
    }).catch(cause => {
      if (pending === request) { value.value = null; loadedAt.value = null; error.value = cause instanceof Error ? cause.message : '首页数据加载失败' }
      throw cause
    }).finally(() => { if (pending === request) pending = undefined })
    pending = request
    return request.promise
  }
  return { snapshot, error, loadedAt, load }
}
