import { httpClient, HttpMethod } from '@activepieces/pieces-common';

interface ApiConfig {
  baseUrl: string;
  apiKey: string;
}

/**
 * Fetch all pieces from the platform API.
 */
export async function getAllPieces(config: ApiConfig) {
  try {
    const response = await httpClient.sendRequest({
      method: HttpMethod.GET,
      url: `${config.baseUrl}/api/v1/pieces`,
      headers: {
        Authorization: `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json',
      },
    });
    return response.body || [];
  } catch (error) {
    console.error('Failed to fetch pieces:', error);
    return [];
  }
}

/**
 * Return the actions map for a particular piece.
 */
export async function getPieceActions(pieceName: string, config: ApiConfig) {
  const pieces = await getAllPieces(config);
  const piece = pieces.find((p: any) => p.name === pieceName);
  return piece?.actions || {};
}

/**
 * Fetch all MCP pieces from the platform API.
 */
export async function getAllMCPPieces(config: ApiConfig) {
  try {
    const response = await httpClient.sendRequest({
      method: HttpMethod.GET,
      url: `${config.baseUrl}/api/v1/mcp-pieces`,
      headers: {
        Authorization: `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json',
      },
    });
    return response.body || [];
  } catch (error) {
    console.error('Failed to fetch MCP pieces:', error);
    return [];
  }
}

/**
 * Fetch connections for a given piece.
 */
export async function getPieceConnections(pieceName: string, config: ApiConfig) {
  try {
    const response = await httpClient.sendRequest({
      method: HttpMethod.GET,
      url: `${config.baseUrl}/api/v1/connections?pieceName=${pieceName}`,
      headers: {
        Authorization: `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json',
      },
    });

    const connections = response.body || [];
    return connections.filter((c: any) => c.pieceName === pieceName);
  } catch (error) {
    console.error('Failed to fetch connections:', error);
    return [];
  }
}
