import axios, { InternalAxiosRequestConfig } from 'axios'
import { generateSignatureHeaders } from './signature'
import { checkApiPermission } from './permission'

const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    
    const method = config.method?.toUpperCase() || 'GET'
    let url = config.url || ''
    const body = config.data
    
    if (config.params && Object.keys(config.params).length > 0) {
      const queryParams = new URLSearchParams()
      Object.entries(config.params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          queryParams.append(key, String(value))
        }
      })
      const queryString = queryParams.toString()
      if (queryString) {
        url += (url.includes('?') ? '&' : '?') + queryString
      }
    }
    
    const fullPath = `/api${url.startsWith('/') ? url : '/' + url}`
    const signatureHeaders = generateSignatureHeaders(method, fullPath, body)
    
    config.headers = config.headers || {}
    Object.assign(config.headers, signatureHeaders)
    
    if (!checkApiPermission(method, url)) {
      const error = new Error('无权限访问此接口')
      ;(error as any).response = {
        status: 403,
        data: { message: '无权限访问此接口' }
      }
      return Promise.reject(error)
    }
    
    return config
  },
  (error) => Promise.reject(error)
)

request.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      if (!window.location.pathname.includes('/login')) {
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

export default request