import { useToast } from '../composables/useToast'
import { authUtils } from './auth'
import router from '../router'

const BASE_URL = 'https://domaintestaccount.store'

class Http {
  constructor() {
    this.baseURL = BASE_URL
    this.headers = {
      'Content-Type': 'application/json'
    }
  }

  setToken(token) {
    if (token) {
      this.headers.Authorization = `Bearer ${token}`
    } else {
      delete this.headers.Authorization
    }
  }

  async refreshToken() {
    try {
      const refreshToken = authUtils.decrypt(localStorage.getItem('refreshToken'))
      if (!refreshToken) {
        throw new Error('No refresh token available')
      }

      const response = await fetch(this.baseURL + '/api/v1/auth/refresh', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ refresh_token: refreshToken })
      })

      if (!response.ok) {
        throw new Error('Token refresh failed')
      }

      const data = await response.json()
      localStorage.setItem('token', authUtils.encrypt(data.access_token))
      if (data.refresh_token) {
        localStorage.setItem('refreshToken', authUtils.encrypt(data.refresh_token))
      }
      this.setToken(data.access_token)
      return data.access_token
    } catch (error) {
      console.error('Token refresh failed:', error)
      throw error
    }
  }

  async request(endpoint, options = {}) {
    const { showToast } = useToast()
    const url = this.baseURL + endpoint

    // 在发送请求前检查并获取最新的token
    const encryptedToken = localStorage.getItem('token')
    if (encryptedToken) {
      const token = authUtils.decrypt(encryptedToken)
      if (token && authUtils.isTokenNearExpiry(token)) {
        try {
          await this.refreshToken()
        } catch (error) {
          console.error('Token refresh failed:', error)
        }
      }
      this.setToken(authUtils.decrypt(localStorage.getItem('token')))
    }

    const headers = {
      ...this.headers,
      ...options.headers
    }

    try {
      const response = await fetch(url, {
        ...options,
        headers
      })

      // 处理401错误
      if (response.status === 401) {
        try {
          // 尝试刷新token
          await this.refreshToken()
          
          // 使用新token重试请求
          const retryResponse = await fetch(url, {
            ...options,
            headers: {
              ...options.headers,
              ...this.headers
            }
          })
          
          if (retryResponse.ok) {
            return await retryResponse.json()
          }
          
          throw new Error('登录已过期，请重新登录')
        } catch (error) {
          // 刷新token失败，清除认证信息并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('refreshToken')
          localStorage.removeItem('user')
          authUtils.broadcastAuthChange('logout')
          router.push('/login')
          throw new Error('登录已过期，请重新登录')
        }
      }

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.detail || data.message || '请求失败')
      }

      return data
    } catch (error) {
      console.error('Request failed:', error)
      showToast(error.message, 'error')
      throw error
    }
  }

  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' })
  }

  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }

  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' })
  }
}

export const http = new Http()
