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

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  withCredentials: true,
})

api.interceptors.response.use(
  (res) => res,
  (err) => {
    const msg = err.response?.data?.error || err.message || '请求失败'
    if (err.response?.status === 401) {
      refreshAuth()
      window.location.href = '/login'
      return Promise.reject(err)
    }
    ElMessage.error(msg)
    return Promise.reject(err)
  }
)

export default api

export let uiRefreshInterval = 10000

export const checkAuth = () => api.get('/auth/me').then(res => {
  if (res.data && typeof res.data.ui_refresh_interval === 'number') {
    uiRefreshInterval = res.data.ui_refresh_interval
  }
  return res
})
export const login = (data) => api.post('/auth/login', data)
export const guestLogin = () => api.post('/auth/guest')
export const logout = () => api.post('/auth/logout')

export const fetchMachines = (params) => api.get('/machines', { params })
export const fetchMachine = (id) => api.get(`/machines/${id}`)
export const createMachine = (data) => api.post('/machines', data)
export const updateMachine = (id, data) => api.put(`/machines/${id}`, data)
export const deleteMachine = (id) => api.delete(`/machines/${id}`)
export const sshInfo = (id, data) => api.post(`/machines/${id}/ssh-info`, data)
export const syncSSH = (id, data) => api.post(`/machines/${id}/sync-ssh`, data)
export const fetchOfflineLogs = (id) => api.get(`/machines/${id}/offline-logs`)

export const fetchServices = (machineId) => api.get(`/machines/${machineId}/services`)
export const fetchAllServices = () => api.get('/services')
export const createService = (machineId, data) => api.post(`/machines/${machineId}/services`, data)
export const updateService = (id, data) => api.put(`/services/${id}`, data)
export const deleteService = (id) => api.delete(`/services/${id}`)

export const fetchRelationships = () => api.get('/relationships')
export const createRelationship = (data) => api.post('/relationships', data)
export const updateRelationship = (id, data) => api.put(`/relationships/${id}`, data)
export const deleteRelationship = (id) => api.delete(`/relationships/${id}`)

export const fetchLogs = (params) => api.get('/logs', { params })

export const exportData = () => api.get('/export', { responseType: 'blob' })
export const importData = (formData) => api.post('/import', formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
})
