import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
api.interceptors.request.use(
  config => config,
  error => Promise.reject(error)
)

// Response interceptor
api.interceptors.response.use(
  response => response.data,
  error => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// Server API
export const serverApi = {
  getAll: () => api.get('/servers'),
  getAllActive: () => api.get('/servers/active'),
  getById: (id) => api.get(`/servers/${id}`),
  create: (data) => api.post('/servers', data),
  update: (id, data) => api.put(`/servers/${id}`, data),
  delete: (id) => api.delete(`/servers/${id}`),
  testConnection: (id) => api.post(`/servers/${id}/test-connection`)
}

// LogPath API
export const logPathApi = {
  getByServerId: (serverId) => api.get(`/log-paths/server/${serverId}`),
  getActiveByServerId: (serverId) => api.get(`/log-paths/server/${serverId}/active`),
  getById: (id) => api.get(`/log-paths/${id}`),
  create: (data) => api.post('/log-paths', data),
  update: (id, data) => api.put(`/log-paths/${id}`, data),
  delete: (id) => api.delete(`/log-paths/${id}`)
}

// Pattern API
export const patternApi = {
  getAll: () => api.get('/patterns'),
  getAllActive: () => api.get('/patterns/active'),
  getById: (id) => api.get(`/patterns/${id}`),
  create: (data) => api.post('/patterns', data),
  update: (id, data) => api.put(`/patterns/${id}`, data),
  delete: (id) => api.delete(`/patterns/${id}`),
  test: (regex, sampleText) => api.post('/patterns/test', null, { params: { regex, sampleText } })
}

// Setting API
export const settingApi = {
  getAll: () => api.get('/settings'),
  getAllAsMap: () => api.get('/settings/map'),
  getValue: (key) => api.get(`/settings/${key}`),
  save: (data) => api.post('/settings', data),
  saveAll: (settings) => api.put('/settings', settings),
  delete: (key) => api.delete(`/settings/${key}`)
}

// Scan API
export const scanApi = {
  // SSE 기반 스캔 시작 (진행상황 실시간 수신)
  startWithProgress: (serverId, onProgress, onComplete, onError) => {
    const eventSource = new EventSource(`/api/scan/start/${serverId}`)
    
    eventSource.addEventListener('progress', (event) => {
      const progress = JSON.parse(event.data)
      onProgress && onProgress(progress)
    })
    
    eventSource.addEventListener('complete', (event) => {
      const result = JSON.parse(event.data)
      onComplete && onComplete(result)
      eventSource.close()
    })
    
    eventSource.addEventListener('error', (event) => {
      if (event.data) {
        onError && onError(event.data)
      }
      eventSource.close()
    })
    
    eventSource.onerror = () => {
      eventSource.close()
    }
    
    return eventSource
  },
  
  // SSE 기반 전체 서버 스캔
  startAllWithProgress: (onProgress, onComplete, onError) => {
    const eventSource = new EventSource('/api/scan/start-all')
    
    eventSource.addEventListener('progress', (event) => {
      const progress = JSON.parse(event.data)
      onProgress && onProgress(progress)
    })
    
    eventSource.addEventListener('complete', (event) => {
      const results = JSON.parse(event.data)
      onComplete && onComplete(results)
      eventSource.close()
    })
    
    eventSource.addEventListener('error', (event) => {
      if (event.data) {
        onError && onError(event.data)
      }
      eventSource.close()
    })
    
    eventSource.onerror = () => {
      eventSource.close()
    }
    
    return eventSource
  },
  
  // 동기 방식 스캔 (간단 실행)
  execute: (serverId) => api.post(`/scan/execute/${serverId}`),
  
  // 진행 상황 조회
  getProgress: (serverId) => api.get(`/scan/progress/${serverId}`),
  
  // 스캔 이력 조회
  getHistory: (serverId) => api.get(`/scan/history/${serverId}`),
  
  // 분석 결과 초기화
  reset: (serverId) => api.delete(`/scan/reset/${serverId}`),
  resetAll: () => api.delete('/scan/reset-all'),
  
  // 에러 통계
  getStatsByFile: (serverId) => api.get('/scan/stats/by-file', { params: { serverId } }),
  getStatsByServer: () => api.get('/scan/stats/by-server'),
  getStatsByPattern: (serverId) => api.get('/scan/stats/by-pattern', { params: { serverId } }),
  
  // 대시보드용: 서버별 최근 N일 일별 통계
  getDailyStatsByServer: (days = 30) => api.get('/scan/stats/daily-by-server', { params: { days } }),
  
  // 월별현황용: 서버별 해당 월 일별 통계
  getMonthlyStatsByServer: (year, month) => api.get('/scan/stats/monthly-by-server', { params: { year, month } }),
  
  // 일별현황용: 서버별 해당 날짜 5분 단위 통계
  getTimeStatsByServer: (date, intervalMinutes = 5) => api.get('/scan/stats/time-by-server', { params: { date, intervalMinutes } })
}

// ErrorLog API
export const errorLogApi = {
  search: (params) => api.get('/error-logs', { params }),
  getById: (id) => api.get(`/error-logs/${id}`),
  getByServer: (serverId, params) => api.get(`/error-logs/server/${serverId}`, { params }),
  getTree: () => api.get('/error-logs/tree'),
  getFiles: (serverId) => api.get('/error-logs/files', { params: { serverId } }),
  deleteByIds: (ids) => api.delete('/error-logs/batch', { data: ids }),
  deleteByFile: (serverId, filePath) => api.delete('/error-logs/by-file', { params: { serverId, filePath } })
}

// Export API (Step 5에서 구현 예정)
export const exportApi = {
  exportHtml: (params) => api.post('/export/html', params, { responseType: 'blob' }),
  exportTxt: (params) => api.post('/export/txt', params, { responseType: 'blob' })
}

export default api
