import { apiClient } from "./client";
import type {
  Exchange,
  ExchangeCreateRequest,
  ExchangeUpdateRequest,
} from "../types/models";

interface ExchangeResponse {
  [id: string]: {
    exchange: string;
    name: string;
    api_key: string;
    testnet: boolean;
    enabled: boolean;
    created_at: string;
    updated_at: string;
  };
}

export async function getExchanges(): Promise<Exchange[]> {
  const response = await apiClient.get<ExchangeResponse>("/api/exchanges");
  const data = response.data;
  // Convert object to array
  return Object.entries(data).map(([id, config]) => ({
    id,
    type: config.exchange as Exchange["type"],
    name: config.name,
    apiKey: config.api_key,
    testnet: config.testnet,
    enabled: config.enabled,
    status: config.enabled ? "connected" : "disconnected",
    createdAt: config.created_at,
    updatedAt: config.updated_at,
  }));
}

export async function getExchange(id: string): Promise<Exchange> {
  const response = await apiClient.get<Exchange>(`/api/exchanges/${id}`);
  return response.data;
}

export async function createExchange(
  data: ExchangeCreateRequest,
): Promise<Exchange> {
  const response = await apiClient.post<Exchange>("/api/exchanges", data);
  return response.data;
}

export async function updateExchange(
  id: string,
  data: ExchangeUpdateRequest,
): Promise<Exchange> {
  const response = await apiClient.put<Exchange>(`/api/exchanges/${id}`, data);
  return response.data;
}

export async function deleteExchange(id: string): Promise<void> {
  await apiClient.delete(`/api/exchanges/${id}`);
}

export async function testExchangeConnection(
  id: string,
): Promise<{ success: boolean; message: string }> {
  const response = await apiClient.post<{ success: boolean; message: string }>(
    `/api/exchanges/${id}/test`,
  );
  return response.data;
}
