import axios from 'axios'

export interface Service {
  id: string
  service_id: string
  name: string
  algorithm_name: string
  version: string
  host: string
  port: number
  api_url: string
  status: string
  created_at: string
  updated_at: string | null
}

export interface ServiceOperationResponse {
  success: boolean
  message: string
  service_id: string
  status: string
}

export interface ServiceListResponse {
  success: boolean
  message: string
  services: Service[]
  total: number
}

export interface RegisterServiceRequest {
  repository_id: string
  name: string
  version: string
  service_type: string
  host: string
  port: number
  timeout: number
  health_check_path: string
  environment: Record<string, any>
}

export interface RegisterServiceResponse {
  success: boolean
  message: string
  service: Service
}

export interface DeleteServiceResponse {
  success: boolean
  message: string
  service_id: string
}

const BASE_URL = '/api/v1/services'

export const serviceManagementApi = {
  getServices: async (): Promise<ServiceListResponse> => {
    const response = await axios.get<ServiceListResponse>(BASE_URL)
    return response.data
  },

  registerService: async (data: RegisterServiceRequest): Promise<RegisterServiceResponse> => {
    const response = await axios.post<RegisterServiceResponse>(`${BASE_URL}/register`, data)
    return response.data
  },

  startService: async (serviceId: string): Promise<ServiceOperationResponse> => {
    const response = await axios.post<ServiceOperationResponse>(`${BASE_URL}/${serviceId}/start`)
    return response.data
  },

  stopService: async (serviceId: string): Promise<ServiceOperationResponse> => {
    const response = await axios.post<ServiceOperationResponse>(`${BASE_URL}/${serviceId}/stop`)
    return response.data
  },

  restartService: async (serviceId: string): Promise<ServiceOperationResponse> => {
    const response = await axios.post<ServiceOperationResponse>(`${BASE_URL}/${serviceId}/restart`)
    return response.data
  },

  deleteService: async (serviceId: string): Promise<DeleteServiceResponse> => {
    const response = await axios.delete<DeleteServiceResponse>(`${BASE_URL}/${serviceId}`)
    return response.data
  },

  getServiceDetail: async (serviceId: string): Promise<Service> => {
    const response = await axios.get<{ success: boolean; message: string; service: Service }>(`${BASE_URL}/${serviceId}`)
    return response.data.service
  }
}

export default serviceManagementApi