import { apiClient } from './client'
import { StrategyCreate, StrategyUpdate, StrategyResponse } from '../types'

export const strategiesApi = {
  listStrategies: async (): Promise<StrategyResponse[]> => {
    const response = await apiClient.get('/api/strategies/')
    return response.data
  },

  getAvailableStrategies: async (): Promise<{ strategies: string[] }> => {
    const response = await apiClient.get('/api/strategies/available')
    return response.data
  },

  createStrategy: async (strategy: StrategyCreate): Promise<StrategyResponse> => {
    const response = await apiClient.post('/api/strategies/', strategy)
    return response.data
  },

  getStrategy: async (strategyId: number): Promise<StrategyResponse> => {
    const response = await apiClient.get(`/api/strategies/${strategyId}`)
    return response.data
  },

  updateStrategy: async (strategyId: number, updates: StrategyUpdate): Promise<StrategyResponse> => {
    const response = await apiClient.put(`/api/strategies/${strategyId}`, updates)
    return response.data
  },

  deleteStrategy: async (strategyId: number): Promise<void> => {
    await apiClient.delete(`/api/strategies/${strategyId}`)
  },

  startStrategy: async (strategyId: number): Promise<void> => {
    await apiClient.post(`/api/strategies/${strategyId}/start`)
  },

  stopStrategy: async (strategyId: number): Promise<void> => {
    await apiClient.post(`/api/strategies/${strategyId}/stop`)
  },

  getStrategyStatus: async (strategyId: number): Promise<StrategyStatusResponse> => {
    const response = await apiClient.get(`/api/strategies/${strategyId}/status`)
    return response.data
  },

  getRunningStrategies: async (): Promise<RunningStrategiesResponse> => {
    const response = await apiClient.get('/api/strategies/running/all')
    return response.data
  },
}

export interface StrategyStatusResponse {
  strategy_id: number
  name: string
  type: string
  symbol: string | null
  running: boolean
  enabled?: boolean
  started_at?: string
  last_tick?: string
  last_signal?: {
    type: string
    strength: number
    price: number
    timestamp: string
    metadata?: Record<string, any>
  }
  signal_count?: number
  error_count?: number
}

export interface RunningStrategiesResponse {
  total_running: number
  strategies: StrategyStatusResponse[]
}
