import { get, post } from '@/utils/request'

/**
 * 现货资产接口响应解包（兼容 data / data.data / 顶层）
 */
export function unwrapSpotAssetPayload(raw: unknown): Record<string, unknown> | null {
  if (!raw || typeof raw !== 'object') {
    return null
  }
  const o = raw as Record<string, unknown>
  if ('assetList' in o && Array.isArray(o.assetList)) {
    return o
  }
  const d = o.data
  if (d && typeof d === 'object' && 'assetList' in (d as object)) {
    return d as Record<string, unknown>
  }
  return o
}

/** 解析现货各币种可用余额 */
export function parseSpotAvailableMap(raw: unknown): Record<string, string> {
  const inner = unwrapSpotAssetPayload(raw)
  const list = inner?.assetList
  const map: Record<string, string> = {}
  if (!Array.isArray(list)) {
    return map
  }
  for (const item of list) {
    if (!item || typeof item !== 'object') {
      continue
    }
    const row = item as Record<string, unknown>
    const coin = String(row.symbol ?? row.coinId ?? row.coin ?? '').toUpperCase().trim()
    if (!coin) {
      continue
    }
    const avail = row.available ?? row.balance
    map[coin] = String(avail ?? '0')
  }
  return map
}

/** 现货交易账户 USDT 可用（划转接口用） */
export function extractUsdtAvailableFromSpotAssets(raw: unknown): string {
  return parseSpotAvailableMap(raw).USDT ?? '0'
}

/** 现货币种开放列表（划转可选币种） */
export function parseOpenCoinSymbols(raw: unknown): string[] {
  const arr = Array.isArray(raw)
    ? raw
    : Array.isArray((raw as { data?: unknown })?.data)
      ? (raw as { data: unknown[] }).data
      : []
  const set = new Set<string>()
  for (const item of arr) {
    if (!item || typeof item !== 'object') {
      continue
    }
    const o = item as Record<string, unknown>
    const sym = String(o.symbol ?? o.coinSymbol ?? '').toUpperCase().trim()
    if (sym) {
      set.add(sym)
    }
  }
  const list = [...set]
  list.sort((a, b) => {
    if (a === 'USDT') return -1
    if (b === 'USDT') return 1
    return a.localeCompare(b)
  })
  return list.length ? list : ['USDT']
}

/** 资金账户各币种可用余额 */
export function parseFundWalletBalances(raw: unknown): Record<string, string> {
  const arr = Array.isArray(raw)
    ? raw
    : Array.isArray((raw as { data?: unknown })?.data)
      ? (raw as { data: unknown[] }).data
      : []
  const map: Record<string, string> = {}
  for (const item of arr) {
    if (!item || typeof item !== 'object') {
      continue
    }
    const row = item as Record<string, unknown>
    const coin = row.coin as Record<string, unknown> | undefined
    const unit = String(row.coinUnit ?? coin?.unit ?? coin?.name ?? row.unit ?? '')
      .toUpperCase()
      .trim()
    if (!unit) {
      continue
    }
    const bal = row.balance ?? row.available ?? row.useBalance
    map[unit] = String(bal ?? '0')
  }
  return map
}

export interface SpotTransferAssetContext {
  openCoins: string[]
  spotAvailable: Record<string, string>
  fundAvailable: Record<string, string>
}

/** 加载资金↔现货划转所需币种与余额 */
export async function loadSpotTransferAssetContext(): Promise<SpotTransferAssetContext> {
  const [coinsRaw, spotRaw, fundRaw] = await Promise.all([
    get<unknown>('spot/v1/config/coin/list').catch(() => null),
    get<unknown>('spot/v1/account/asset/list').catch(() => null),
    post<unknown>('/uc/asset/wallet', {}).catch(() => null),
  ])
  return {
    openCoins: parseOpenCoinSymbols(coinsRaw),
    spotAvailable: parseSpotAvailableMap(spotRaw),
    fundAvailable: parseFundWalletBalances(fundRaw),
  }
}

/** 是否涉及资金账户与现货交易账户之间的划转 */
export function involvesSpotTradingBridge(from: string, to: string): boolean {
  return from === 'SPOT_TRADING' || to === 'SPOT_TRADING'
}
