import { api } from './client'
import { createCachedGetter } from './cache'

const serverInfoGetter = createCachedGetter(async () => {
  const { data } = await api.get('/server/info')
  return data
}, 30_000)

const dockerStatsGetter = createCachedGetter(async () => {
  const { data } = await api.get('/docker_stats')
  return data
}, 8_000)

const requestMetricsGetter = createCachedGetter(async () => {
  const { data } = await api.get('/request_metrics')
  return data
}, 10_000)

const slowSqlMetricsGetter = createCachedGetter(async () => {
  const { data } = await api.get('/slow_sql_metrics')
  return data
}, 10_000)

const taskStatsGetter = createCachedGetter(async () => {
  const { data } = await api.get('/task/stats')
  return data
}, 4_000)

const runningTasksGetter = createCachedGetter(async () => {
  const { data } = await api.get('/task/running')
  return data
}, 2_000)

export async function fetchServerInfo(options = {}) {
  return serverInfoGetter.run(options)
}

export async function fetchDockerStats(options = {}) {
  return dockerStatsGetter.run(options)
}

export async function fetchRequestMetrics(options = {}) {
  return requestMetricsGetter.run(options)
}

export async function fetchSlowSqlMetrics(options = {}) {
  return slowSqlMetricsGetter.run(options)
}

export async function fetchTaskStats(options = {}) {
  return taskStatsGetter.run(options)
}

export async function fetchRunningTasks(options = {}) {
  return runningTasksGetter.run(options)
}

export async function fetchTaskLogs(params) {
  const { data } = await api.get('/task/logs', { params })
  return data
}

export async function clearOldTaskLogs(days) {
  const { data } = await api.post('/task/logs/clear', { days })
  taskStatsGetter.clear()
  runningTasksGetter.clear()
  return data
}
