import request from '@/utils/request'
import type { ApiResult } from '@/api/index'

// 用户余额信息
export interface UserBalance {
  balance: string
  frozenBalance: string
  totalIncome: string
  totalExpense: string
}

// 用户积分信息
export interface UserPoints {
  points: number
  totalEarned: number
  totalUsed: number
  expiringSoon: number
}

// 用户优惠券统计
export interface UserCoupons {
  count: number
  available: number
  used: number
  expired: number
}

// 用户礼品卡统计
export interface UserGiftCards {
  count: number
  unused: number
  used: number
  expired: number
}

// 用户订单统计
export interface UserOrderStats {
  pending: number
  paid: number
  shipped: number
  completed: number
  refund: number
  total: number
}

// 用户完整数据
export interface UserDashboard {
  balance: UserBalance
  points: UserPoints
  coupons: UserCoupons
  giftCards: UserGiftCards
  orders: UserOrderStats
  lastUpdateTime: string
}

/**
 * 获取用户余额信息
 */
export async function getUserBalance() {
  const res = await request.get<ApiResult<UserBalance>>('/user/balance')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取用户积分信息
 */
export async function getUserPoints() {
  const res = await request.get<ApiResult<UserPoints>>('/user/points')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取用户优惠券统计
 */
export async function getUserCoupons() {
  const res = await request.get<ApiResult<UserCoupons>>('/user/coupons/stats')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取用户礼品卡统计
 */
export async function getUserGiftCards() {
  const res = await request.get<ApiResult<UserGiftCards>>('/user/gift-cards/stats')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取用户订单统计
 */
export async function getUserOrderStats() {
  const res = await request.get<ApiResult<UserOrderStats>>('/user/orders/stats')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取用户完整仪表板数据（一次性获取所有数据）
 */
export async function getUserDashboard() {
  const res = await request.get<ApiResult<UserDashboard>>('/user/dashboard')
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 刷新用户数据缓存
 */
export async function refreshUserData() {
  const res = await request.post<ApiResult<unknown>>('/user/refresh-cache')
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}
