/**
 * 本地存储封装
 * 统一封装 uni.setStorage / uni.getStorage 等API
 */
class Storage {
  constructor(prefix = 'ph_') {
    this.prefix = prefix
  }

  /**
   * 获取完整的存储Key
   */
  _getKey(key) {
    // 如果key已经包含前缀，直接返回
    if (key.startsWith(this.prefix)) {
      return key
    }
    return `${this.prefix}${key}`
  }

  /**
   * 同步获取数据
   */
  get(key, defaultValue = null) {
    try {
      const data = uni.getStorageSync(this._getKey(key))
      if (data === '' || data === undefined || data === null) {
        return defaultValue
      }
      return data
    } catch (error) {
      console.warn('[PostHog Storage] Get error:', error)
      return defaultValue
    }
  }

  /**
   * 同步设置数据
   */
  set(key, value) {
    try {
      uni.setStorageSync(this._getKey(key), value)
      return true
    } catch (error) {
      console.warn('[PostHog Storage] Set error:', error)
      return false
    }
  }

  /**
   * 同步删除数据
   */
  remove(key) {
    try {
      uni.removeStorageSync(this._getKey(key))
      return true
    } catch (error) {
      console.warn('[PostHog Storage] Remove error:', error)
      return false
    }
  }

  /**
   * 异步获取数据
   */
  async getAsync(key, defaultValue = null) {
    return new Promise((resolve) => {
      uni.getStorage({
        key: this._getKey(key),
        success: (res) => {
          resolve(res.data ?? defaultValue)
        },
        fail: () => {
          resolve(defaultValue)
        },
      })
    })
  }

  /**
   * 异步设置数据
   */
  async setAsync(key, value) {
    return new Promise((resolve) => {
      uni.setStorage({
        key: this._getKey(key),
        data: value,
        success: () => resolve(true),
        fail: () => resolve(false),
      })
    })
  }

  /**
   * 清除所有PostHog相关存储
   */
  clear() {
    try {
      const res = uni.getStorageInfoSync()
      const keys = res.keys || []
      keys.forEach((key) => {
        if (key.startsWith(this.prefix)) {
          uni.removeStorageSync(key)
        }
      })
      return true
    } catch (error) {
      console.warn('[PostHog Storage] Clear error:', error)
      return false
    }
  }

  /**
   * 获取JSON数据
   */
  getJSON(key, defaultValue = null) {
    const data = this.get(key)
    if (data === null) return defaultValue
    try {
      return typeof data === 'string' ? JSON.parse(data) : data
    } catch {
      return defaultValue
    }
  }

  /**
   * 设置JSON数据
   */
  setJSON(key, value) {
    return this.set(key, JSON.stringify(value))
  }
}

// 导出单例
export default new Storage('ph_')