// Token 存储管理
const STORAGE_KEYS = {
  ACCESS_TOKEN: 'bookmark_access_token',
  REFRESH_TOKEN: 'bookmark_refresh_token',
  TOKEN_EXPIRES: 'bookmark_token_expires',
  USER_INFO: 'bookmark_user_info',
  DEVICE_INFO: 'bookmark_device_info',
  SETTINGS: 'bookmark_settings'
}

export const storage = {
  // 获取访问令牌
  async getAccessToken() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.ACCESS_TOKEN)
    return result[STORAGE_KEYS.ACCESS_TOKEN] || null
  },

  // 设置访问令牌
  async setAccessToken(token) {
    await chrome.storage.local.set({ [STORAGE_KEYS.ACCESS_TOKEN]: token })
  },

  // 获取刷新令牌
  async getRefreshToken() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.REFRESH_TOKEN)
    return result[STORAGE_KEYS.REFRESH_TOKEN] || null
  },

  // 设置刷新令牌
  async setRefreshToken(token) {
    await chrome.storage.local.set({ [STORAGE_KEYS.REFRESH_TOKEN]: token })
  },

  // 获取令牌过期时间
  async getTokenExpires() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.TOKEN_EXPIRES)
    return result[STORAGE_KEYS.TOKEN_EXPIRES] || null
  },

  // 设置令牌过期时间
  async setTokenExpires(expires) {
    await chrome.storage.local.set({ [STORAGE_KEYS.TOKEN_EXPIRES]: expires })
  },

  // 检查令牌是否过期
  async isTokenExpired() {
    const expires = await this.getTokenExpires()
    if (!expires) return true
    return new Date(expires) <= new Date()
  },

  // 清除所有令牌
  async clearTokens() {
    await chrome.storage.local.remove([
      STORAGE_KEYS.ACCESS_TOKEN,
      STORAGE_KEYS.REFRESH_TOKEN,
      STORAGE_KEYS.TOKEN_EXPIRES
    ])
  },

  // 获取用户信息
  async getUserInfo() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.USER_INFO)
    return result[STORAGE_KEYS.USER_INFO] || null
  },

  // 设置用户信息
  async setUserInfo(user) {
    await chrome.storage.local.set({ [STORAGE_KEYS.USER_INFO]: user })
  },

  // 获取设备信息
  async getDeviceInfo() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.DEVICE_INFO)
    return result[STORAGE_KEYS.DEVICE_INFO] || null
  },

  // 设置设备信息
  async setDeviceInfo(device) {
    await chrome.storage.local.set({ [STORAGE_KEYS.DEVICE_INFO]: device })
  },

  // 获取设置
  async getSettings() {
    const result = await chrome.storage.local.get(STORAGE_KEYS.SETTINGS)
    return result[STORAGE_KEYS.SETTINGS] || {
      autoSync: true,
      syncDelete: false,
      showNotification: true
    }
  },

  // 保存设置
  async setSettings(settings) {
    await chrome.storage.local.set({ [STORAGE_KEYS.SETTINGS]: settings })
  },

  // 检查是否已登录
  async isLoggedIn() {
    const token = await this.getAccessToken()
    const expired = await this.isTokenExpired()
    return !!token && !expired
  }
}

export default storage

