import axios from 'axios'

export interface EnvironmentConfig {
  jingrow_server_url: string
  jingrow_api_key: string
  jingrow_api_secret: string
  jingrow_cloud_url: string
  jingrow_cloud_api_url: string
  jingrow_cloud_api_key: string
  jingrow_cloud_api_secret: string
  jingrow_db_host: string
  jingrow_db_port: string
  jingrow_db_name: string
  jingrow_db_user: string
  jingrow_db_password: string
  jingrow_db_type: string
  qdrant_host: string
  qdrant_port: number
  run_mode: string
  environment: string
  log_level: string
  backend_host: string
  backend_port: number
  backend_reload: boolean
  worker_processes: number
  worker_threads: number
  watch: boolean
}

// 获取环境配置
export const getEnvironmentConfig = async (): Promise<{ success: boolean; data?: EnvironmentConfig; message?: string }> => {
  try {
    const response = await axios.get(
      `/jingrow/system/environment-config`)

    if (response.data?.success) {
      return { success: true, data: response.data.data }
    }
    return { success: false, message: response.data?.message || '获取环境配置失败' }
  } catch (error: any) {
    if (error.response?.status === 403) {
      return { success: false, message: '仅系统管理员可以访问此功能' }
    }
    if (error.response?.status === 401) {
      return { success: false, message: '认证失败，请重新登录' }
    }
    return { success: false, message: error.response?.data?.detail || error.message || '获取环境配置失败' }
  }
}

// 更新环境配置
export const updateEnvironmentConfig = async (config: Partial<EnvironmentConfig>): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/system/environment-config`, config)

    if (response.data?.success) {
      return { success: true, message: response.data.message || '环境配置已更新' }
    }
    return { success: false, message: response.data?.message || '更新环境配置失败' }
  } catch (error: any) {
    if (error.response?.status === 403) {
      return { success: false, message: '仅系统管理员可以访问此功能' }
    }
    if (error.response?.status === 401) {
      return { success: false, message: '认证失败，请重新登录' }
    }
    return { success: false, message: error.response?.data?.detail || error.message || '更新环境配置失败' }
  }
}

// 重启环境
export const restartEnvironment = async (): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/system/restart-environment`, {})

    if (response.data?.success) {
      return { success: true, message: response.data.message || '环境重启请求已提交' }
    }
    return { success: false, message: response.data?.message || '重启环境失败' }
  } catch (error: any) {
    if (error.response?.status === 403) {
      return { success: false, message: '仅系统管理员可以访问此功能' }
    }
    if (error.response?.status === 401) {
      return { success: false, message: '认证失败，请重新登录' }
    }
    return { success: false, message: error.response?.data?.detail || error.message || '重启环境失败' }
  }
}

