import { apiClient } from "./client";

export interface ExternalConnection {
  id: number;
  connection_name: string;
  description?: string;
  db_type: string;
  host: string;
  port: number;
  database_name: string;
}

export interface ExternalTable {
  table_name: string;
  table_type?: string;
  schema?: string;
}

export interface ExternalColumn {
  column_name: string;
  data_type: string;
  is_nullable?: string;
  column_default?: string;
}

/**
 * 테스트에 성공한 외부 DB 커넥션 목록 조회
 */
export async function getTestedExternalConnections(): Promise<ExternalConnection[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: ExternalConnection[];
    message?: string;
  }>("/dataflow/node-external-connections/tested");

  if (response.data.success && response.data.data) {
    return response.data.data;
  }

  throw new Error(response.data.message || "커넥션 목록을 조회할 수 없습니다.");
}

/**
 * 특정 외부 DB의 테이블 목록 조회
 */
export async function getExternalTables(connectionId: number): Promise<ExternalTable[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: ExternalTable[];
    message?: string;
  }>(`/dataflow/node-external-connections/${connectionId}/tables`);

  if (response.data.success && response.data.data) {
    return response.data.data;
  }

  throw new Error(response.data.message || "테이블 목록을 조회할 수 없습니다.");
}

/**
 * 특정 외부 DB 테이블의 컬럼 목록 조회
 */
export async function getExternalColumns(connectionId: number, tableName: string): Promise<ExternalColumn[]> {
  const response = await apiClient.get<{
    success: boolean;
    data: ExternalColumn[];
    message?: string;
  }>(`/dataflow/node-external-connections/${connectionId}/tables/${tableName}/columns`);

  if (response.data.success && response.data.data) {
    return response.data.data;
  }

  throw new Error(response.data.message || "컬럼 목록을 조회할 수 없습니다.");
}
