import storage from './storage.js'

const API_BASE_URL = 'http://localhost:5000/api'

// 发送 API 请求
async function request(url, options = {}) {
  const token = await storage.getAccessToken()
  
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers
  }

  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers
  })

  // 处理 401 错误
  if (response.status === 401) {
    // 尝试刷新令牌
    const refreshed = await refreshToken()
    if (refreshed) {
      // 重试请求
      const newToken = await storage.getAccessToken()
      headers['Authorization'] = `Bearer ${newToken}`
      return fetch(`${API_BASE_URL}${url}`, { ...options, headers })
    } else {
      await storage.clearTokens()
      throw new Error('登录已过期，请重新登录')
    }
  }

  return response.json()
}

// 刷新令牌
async function refreshToken() {
  const refreshToken = await storage.getRefreshToken()
  if (!refreshToken) return false

  try {
    const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken })
    })

    const data = await response.json()

    if (data.success) {
      await storage.setAccessToken(data.accessToken)
      await storage.setRefreshToken(data.refreshToken)
      await storage.setTokenExpires(data.expiresAt)
      return true
    }
  } catch (e) {
    console.error('Refresh token failed:', e)
  }

  return false
}

export const api = {
  // 登录
  async login(email, password, deviceInfo) {
    const response = await fetch(`${API_BASE_URL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email,
        password,
        deviceName: deviceInfo.name,
        deviceType: deviceInfo.type,
        deviceFingerprint: deviceInfo.fingerprint
      })
    })

    const data = await response.json()

    if (data.success) {
      await storage.setAccessToken(data.accessToken)
      await storage.setRefreshToken(data.refreshToken)
      await storage.setTokenExpires(data.expiresAt)
      await storage.setUserInfo(data.user)
      await storage.setDeviceInfo(data.device)
    }

    return data
  },

  // 登出
  async logout() {
    try {
      await request('/auth/logout', { method: 'POST' })
    } finally {
      await storage.clearTokens()
      await chrome.storage.local.remove(['bookmark_user_info', 'bookmark_device_info'])
    }
  },

  // 获取书签列表
  async getBookmarks(tag) {
    const params = tag ? `?tag=${encodeURIComponent(tag)}` : ''
    return request(`/bookmarks${params}`)
  },

  // 搜索书签
  async searchBookmarks(keyword) {
    return request(`/bookmarks/search?keyword=${encodeURIComponent(keyword)}`)
  },

  // 创建书签
  async createBookmark(data) {
    return request('/bookmarks', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  },

  // 检查 URL 是否存在
  async checkUrl(url) {
    return request(`/bookmarks/check-url?url=${encodeURIComponent(url)}`)
  },

  // 记录访问
  async recordVisit(id) {
    return request(`/bookmarks/${id}/visit`, { method: 'POST' })
  },

  // 获取标签列表
  async getTags() {
    return request('/tags')
  }
}

export default api

