import { DEFAULT_CONFIG, HTTP_STATUS } from './constants'

/**
 * PostHog HTTP请求封装
 * 专门用于PostHog事件上报，与业务请求隔离
 */
class PostHogHttp {
  constructor() {
    this.baseUrl = ''
    this.apiKey = ''
    this.timeout = DEFAULT_CONFIG.request.timeout
    this.maxRetries = DEFAULT_CONFIG.request.maxRetries
    this.retryDelay = DEFAULT_CONFIG.request.retryDelay
    this.debug = false
  }

  /**
   * 初始化配置
   */
  init(config) {
    this.baseUrl = config.apiHost || ''
    this.apiKey = config.apiKey || ''
    this.timeout = config.request?.timeout || this.timeout
    this.maxRetries = config.request?.maxRetries || this.maxRetries
    this.retryDelay = config.request?.retryDelay || this.retryDelay
    this.debug = config.debug || false
  }

  /**
   * 发送POST请求
   */
  async post(path, data, options = {}) {
    const url = `${this.baseUrl}${path}`
    const retries = options.retries ?? this.maxRetries

    return this._requestWithRetry(url, data, retries)
  }

  /**
   * 带重试的请求
   */
  async _requestWithRetry(url, data, retriesLeft) {
    try {
      return await this._doRequest(url, data)
    } catch (error) {
      // 如果还有重试次数且错误可重试
      if (retriesLeft > 0 && this._isRetryableError(error)) {
        this._log(`Request failed, retrying... (${retriesLeft} left)`)

        // 等待一段时间后重试
        await this._delay(this.retryDelay)

        return this._requestWithRetry(url, data, retriesLeft - 1)
      }

      throw error
    }
  }

  /**
   * 执行实际请求
   */
  _doRequest(url, data) {
    return new Promise((resolve, reject) => {
      this._log('Sending request:', url, data)

      uni.request({
        url,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
        },
        data: {
          api_key: this.apiKey,
          ...data,
        },
        timeout: this.timeout,
        success: (res) => {
          this._log('Response:', res.statusCode, res.data)

          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve({
              success: true,
              statusCode: res.statusCode,
              data: res.data,
            })
          } else {
            reject({
              success: false,
              statusCode: res.statusCode,
              message: `HTTP ${res.statusCode}`,
              data: res.data,
            })
          }
        },
        fail: (error) => {
          this._log('Request failed:', error)
          reject({
            success: false,
            statusCode: 0,
            message: error.errMsg || 'Network error',
            error,
          })
        },
      })
    })
  }

  /**
   * 判断是否为可重试的错误
   */
  _isRetryableError(error) {
    // 网络错误可重试
    if (error.statusCode === 0) return true

    // 服务器错误可重试
    if (error.statusCode >= 500) return true

    // 请求超时可重试
    if (error.message?.includes('timeout')) return true

    return false
  }

  /**
   * 延迟函数
   */
  _delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
  }

  /**
   * 调试日志
   */
  _log(...args) {
    if (this.debug) {
      console.log('[PostHog HTTP]', ...args)
    }
  }

  /**
   * 发送单个事件
   */
  async capture(event, distinctId, properties = {}, timestamp = null) {
    const payload = {
      event,
      distinct_id: distinctId,
      properties,
      timestamp: timestamp || new Date().toISOString(),
    }

    return this.post('/capture/', payload)
  }

  /**
   * 批量发送事件
   */
  async batch(events) {
    if (!events || events.length === 0) {
      return { success: true, message: 'No events to send' }
    }

    const payload = {
      batch: events,
    }

    return this.post('/batch/', payload)
  }

  /**
   * 发送用户标识
   */
  async identify(distinctId, userProperties = {}) {
    const payload = {
      event: '$identify',
      distinct_id: distinctId,
      properties: {
        $set: userProperties.$set || {},
        $set_once: userProperties.$set_once || {},
      },
    }

    return this.post('/capture/', payload)
  }
}

// 导出单例
export default new PostHogHttp()