import kyClient from '@/api/index'
import type { TraceListResponse, TraceResponse } from '@/common/interface/api'
import type { Trace } from '@/common/interface/trace'

// Shared request wrapper for Ky
async function request<T>(promise: Promise<T>): Promise<T> {
  try {
    return await promise
  } catch (err: any) {
    // Extract error details from Ky's error structure
    const message = err.message || 'Unknown error'
    const status = err.response?.status || 'unknown'
    throw new Error(`API error [${status}]: ${message}`)
  }
}

export const API = {
  // Force refresh list on backend side
  reloadTraces: async (): Promise<void> => {
    await request(kyClient.get('traces/reload').then((res) => res.json()))
  },

  // Retrieve the list of traces
  listTraces: async (): Promise<Trace[]> => {
    const response = await request<TraceListResponse>(kyClient.get('traces/list').json())
    return response.data.sort((a, b) => ((b.begin || '') < (a.begin || '') ? -1 : 1))
  },

  // Retrieve the trace by its ID
  getTrace: async (traceId: string): Promise<Trace> => {
    const response = await request<TraceResponse>(
      kyClient.get(`traces/get_trace/${traceId}`).json()
    )
    return response.data
  }
}
