import { defineStore } from 'pinia'
import { ref } from 'vue'
import { get } from '@/utils/request'

/**
 * 跟单模块：当前用户是否为带单员（与 App copyTradingProvider 一致）
 *
 * 数据来源：GET follow/customer/
 * 判定：data 中 trader 优先，否则 traderLevel；转成字符串后等于 "20" 即为带单员。
 */
export function rawTraderLevelFromFollowerItem(item: unknown): string {
  if (!item || typeof item !== 'object') {
    return ''
  }
  const o = item as Record<string, unknown>
  if ('trader' in o && o.trader !== undefined && o.trader !== null) {
    return String(o.trader)
  }
  if ('traderLevel' in o && o.traderLevel !== undefined && o.traderLevel !== null) {
    return String(o.traderLevel)
  }
  return ''
}

export function isTraderFromFollowerItem(item: unknown): boolean {
  return rawTraderLevelFromFollowerItem(item) === '20'
}

export const useCopyTradingStore = defineStore('copyTrading', () => {
  const isTrader = ref(false)

  /**
   * 请求 follow/customer/ 并更新 isTrader
   *
   * @return 解析后的单条 customer 数据，失败或无数据时为 null
   */
  async function fetchFollowerInfo(): Promise<Record<string, unknown> | null> {
    try {
      const res: unknown = await get('/follow/customer/')
      const item = (Array.isArray(res) ? res[0] : res) as Record<string, unknown> | null | undefined
      const normalized = item && typeof item === 'object' ? item : null
      isTrader.value = isTraderFromFollowerItem(normalized)
      return normalized
    } catch {
      isTrader.value = false
      return null
    }
  }

  function reset() {
    isTrader.value = false
  }

  /**
   * 仅根据已拿到的 customer 数据刷新 isTrader（避免重复请求，供带单管理页等与接口同源场景使用）
   */
  function syncIsTraderFromItem(item: unknown) {
    isTrader.value = isTraderFromFollowerItem(item)
  }

  return { isTrader, fetchFollowerInfo, reset, syncIsTraderFromItem }
})
