import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const request = axios.create({
  baseURL: '/api/v1/admin',
  timeout: 30000,
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const { response } = error
    if (response) {
      if (response.status === 401) {
        localStorage.removeItem('admin_token')
        localStorage.removeItem('admin_user')
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
      } else if (response.status === 403) {
        ElMessage.error('没有权限执行此操作')
      } else if (response.data?.detail) {
        ElMessage.error(response.data.detail)
      } else {
        ElMessage.error('请求失败')
      }
    } else {
      ElMessage.error('网络错误')
    }
    return Promise.reject(error)
  }
)

// API 模块
const api = {
  // 认证
  auth: {
    login: data => request.post('/auth/login', data),
    me: () => request.get('/auth/me'),
    changePassword: data => request.post('/auth/change-password', data),
    logout: () => request.post('/auth/logout'),
  },

  // 租户
  tenants: {
    list: params => request.get('/tenants', { params }),
    get: id => request.get(`/tenants/${id}`),
    create: data => request.post('/tenants', data),
    update: (id, data) => request.put(`/tenants/${id}`, data),
    delete: id => request.delete(`/tenants/${id}`),
    enable: id => request.post(`/tenants/${id}/enable`),
    disable: id => request.post(`/tenants/${id}/disable`),
  },

  // 配置
  configs: {
    templates: params => request.get('/configs/templates', { params }),
    groups: () => request.get('/configs/groups'),
    getTenantConfigs: (tenantId, params) => request.get(`/configs/tenants/${tenantId}`, { params }),
    updateConfig: (tenantId, group, key, data) => request.put(`/configs/tenants/${tenantId}/${group}/${key}`, data),
    batchUpdate: (tenantId, data) => request.put(`/configs/tenants/${tenantId}/batch`, data),
    deleteConfig: (tenantId, group, key) => request.delete(`/configs/tenants/${tenantId}/${group}/${key}`),
    refreshCache: tenantId => request.post(`/configs/tenants/${tenantId}/refresh-cache`),
  },

  // 提示词
  prompts: {
    list: params => request.get('/prompts', { params }),
    get: id => request.get(`/prompts/${id}`),
    create: data => request.post('/prompts', data),
    update: (id, data) => request.put(`/prompts/${id}`, data),
    getVersions: id => request.get(`/prompts/${id}/versions`),
    rollback: (id, version) => request.post(`/prompts/${id}/rollback/${version}`),
    getTenantPrompts: tenantId => request.get(`/prompts/tenants/${tenantId}`),
    updateTenantPrompt: (tenantId, promptId, data) => request.put(`/prompts/tenants/${tenantId}/${promptId}`, data),
    deleteTenantPrompt: (tenantId, promptId) => request.delete(`/prompts/tenants/${tenantId}/${promptId}`),
  },

  // 功能开关
  features: {
    getDefaults: () => request.get('/features/defaults'),
    getTenantFeatures: tenantId => request.get(`/features/tenants/${tenantId}`),
    updateFeature: (tenantId, code, data) => request.put(`/features/tenants/${tenantId}/${code}`, data),
    resetFeature: (tenantId, code) => request.delete(`/features/tenants/${tenantId}/${code}`),
    batchUpdate: (tenantId, data) => request.post(`/features/tenants/${tenantId}/batch`, data),
  },
}

export default api

