import type { Ref } from 'vue';

import { computed } from 'vue';

import { formatSourceType, formatTestStatus } from './datacenter-constants';

export interface TreeNode {
  id: string;
  label: string;
  type: 'source' | 'table';
  icon?: string;
  meta?: any;
  children?: TreeNode[];
  isLeaf?: boolean;
}

export function useConnectionTree(sources: Ref<any[]>) {
  const treeData = computed<TreeNode[]>(() => {
    return sources.value.map((source) => {
      return {
        id: `source-${source.id}`,
        label: source.sourceName,
        type: 'source' as const,
        icon: getSourceIcon(source.sourceType),
        meta: {
          ...source,
        },
        children: [],
      };
    });
  });

  function getSourceIcon(sourceType: string): string {
    const iconMap: Record<string, string> = {
      MYSQL: 'db',
      POSTGRESQL: 'db',
      ORACLE: 'db',
      GAUSSDB_NATIVE: 'db',
      GBASE_8A: 'db',
      GBASE_8S: 'db',
      EXCEL: 'file',
      PROJECT_MYSQL: 'db',
    };
    return iconMap[sourceType] || 'db';
  }

  function parseNodeKey(key: string) {
    const [type, ...idParts] = key.split('-');
    const id = idParts.join('-');
    return {
      type: type as 'source' | 'table',
      id: Number(id),
    };
  }

  function getStatusColor(source: any): string {
    if (!source.lastTestStatus) return 'muted';
    return source.lastTestStatus === 'SUCCESS' ? 'success' : 'danger';
  }

  return {
    treeData,
    parseNodeKey,
    getSourceIcon,
    getStatusColor,
    formatSourceType,
    formatTestStatus,
  };
}
