// src/utils/appConnector.js
import {
  connectApplication,
  parseAccessOrigin,
  parseHeader,
  setHttpHeaders,
  isInApp,
} from '@/utils/appBridge.js'
import {
  appConnectionManager,
  isAppConnected,
  getAppHeaderInfo,
} from '@/utils/appConnectionManager.js'
import { getUserId, setUserInfo } from '@/utils/userStore.js'
import { getUserIdentity, getMemberProfile } from '@/api/wallet.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const APP_CONNECTION_TIMEOUT = 18000

/**
 * 默认的连接失败处理函数
 * @param {Error} error - 错误对象
 */
const defaultOnFailed = (error) => {
  if (error.message && error.message.includes('parse access')) {
    router.push({ path: '/not_app', query: { message: error.message } })
  }
}

/**
 * APP连接成功后获取用户信息
 * @private
 */
const fetchUserInfoAfterConnection = async () => {
  try {
    console.debug('👤 Fetching user info after connection...')

    const response = await getMemberProfile()

    if (response && response.status && response.body) {
      // 缓存用户信息
      console.debug('✅ User info cached successfully')
      setUserInfo(response.body, null)
    } else {
      console.warn('⚠️ Failed to get team entry or invalid response')
    }
  } catch (error) {
    // 这里不抛出错误，因为APP连接已经成功
    // 用户信息获取失败可以在后续的身份检查中处理
    console.warn('⚠️ Failed to fetch user info after connection:', error)
  }
}

/**
 * 统一的APP连接工具函数
 * @param {Function} onConnected - 连接成功回调
 * @param {Function} onFailed - 连接失败回调（可选，默认使用通用处理）
 * @returns {Promise<Object>} 连接结果
 */
export const connectToApp = async (onConnected, onFailed = defaultOnFailed) => {
  console.group('🔗 APP Connection Process')
  console.debug('🚀 Starting APP connection...')

  try {
    // 检查是否在APP环境中
    if (!isInApp()) {
      console.debug('🌐 Browser environment detected')
      console.groupEnd()

      await fetchUserInfoAfterConnection() //获取用户信息
      if (onConnected) await onConnected() // 触发连接成功回调

      return { success: true, environment: 'browser' } // 浏览器环境
    }

    // 检查是否已经连接且未过期
    if (isAppConnected()) {
      console.debug('✅ APP already connected and valid')

      // 使用缓存的头部信息
      const cachedHeaderInfo = getAppHeaderInfo()
      if (cachedHeaderInfo) {
        console.debug('🔧 Using cached HTTP headers')
        await setHttpHeaders(cachedHeaderInfo)
      }

      console.groupEnd()

      await fetchUserInfoAfterConnection() //获取用户信息
      if (onConnected) await onConnected() // 触发连接成功回调

      return { success: true, environment: 'app', fromCache: true } // APP环境
    }

    // 检查是否有正在进行的连接
    if (appConnectionManager.isConnecting()) {
      console.debug('⏳ Connection already in progress, waiting...')
      await appConnectionManager.getConnectionPromise()
      console.debug('✅ Connected via existing process')
      console.groupEnd()

      await fetchUserInfoAfterConnection() //获取用户信息
      if (onConnected) await onConnected() // 触发连接成功回调

      return { success: true, environment: 'app', fromCache: true } // APP环境
    }

    // 建立新的APP连接
    console.debug('📱 Establishing new APP connection...')

    const connectionResult = await new Promise((resolve, reject) => {
      let connectionTimer = null
      const clearConnectionTimer = () => {
        if (connectionTimer) {
          clearTimeout(connectionTimer)
          connectionTimer = null
        }
      }

      const connectionPromise = new Promise((connectResolve, connectReject) => {
        connectionTimer = setTimeout(() => {
          appConnectionManager.reset()
          connectReject(new Error('APP connection timeout'))
        }, APP_CONNECTION_TIMEOUT)

        connectApplication(async (access) => {
          try {
            const result = parseAccessOrigin(access)

            if (result.success) {
              // 解析头部信息
              const headerInfo = parseHeader(result.data)

              // 设置HTTP请求头
              console.debug('🔧 Setting HTTP headers...')
              await setHttpHeaders(headerInfo)

              // 标记连接成功
              appConnectionManager.setConnected(headerInfo)

              console.debug('🎉 APP connection established successfully')
              connectResolve({ success: true, environment: 'app', fromCache: false }) // APP环境
            } else {
              console.error('❌ Failed to parse access origin:', result.error)
              appConnectionManager.reset()
              connectReject(new Error(result.error))
            }
          } catch (error) {
            console.error('❌ Connection process failed:', error)
            appConnectionManager.reset()
            connectReject(error)
          }
        })
      })

      // 设置连接状态
      appConnectionManager.setConnecting(connectionPromise)

      connectionPromise
        .then((value) => {
          clearConnectionTimer()
          resolve(value)
        })
        .catch((error) => {
          clearConnectionTimer()
          reject(error)
        })
    })

    console.debug('✅ Connection completed successfully')
    console.groupEnd()

    await fetchUserInfoAfterConnection() //获取用户信息
    if (onConnected) await onConnected() // 触发连接成功回调

    return connectionResult
  } catch (error) {
    console.error('❌ Connection failed:', error)
    console.groupEnd()

    // 触发连接失败回调
    if (onFailed) onFailed(error)

    return { success: false, error: error.message }
  }
}
