import request from '@/utils/request';

/**
 * 数据源类型枚举
 */
export enum DataSourceType {
    JENKINS_SERVERS = 'JENKINS_SERVERS',
    K8S_CLUSTERS = 'K8S_CLUSTERS',
    GIT_REPOSITORIES = 'GIT_REPOSITORIES',
    DOCKER_REGISTRIES = 'DOCKER_REGISTRIES',
    NOTIFICATION_CHANNEL_TYPES = 'NOTIFICATION_CHANNEL_TYPES',
    NOTIFICATION_CHANNELS = 'NOTIFICATION_CHANNELS'
}

/**
 * 数据源配置接口
 */
export interface DataSourceConfig {
    url: string;
    params?: Record<string, any>;
    transform: (data: any) => Array<{ label: string; value: any; [key: string]: any }>;
}

/**
 * 数据源选项接口
 */
export interface DataSourceOption {
    label: string;
    value: any;

    [key: string]: any;
}

/**
 * 数据源配置注册表
 */
export const DATA_SOURCE_REGISTRY: Record<DataSourceType, DataSourceConfig> = {
    [DataSourceType.JENKINS_SERVERS]: {
        url: '/api/v1/external-system/list',
        params: {type: 'JENKINS', enabled: true},
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: `${item.name} (${item.url})`,
                value: item.id,
                url: item.url,
                name: item.name
            }));
        }
    },
    [DataSourceType.NOTIFICATION_CHANNEL_TYPES]: {
        url: '/api/v1/notification-channel/types',
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: `${item.label}`,
                value: item.code
            }));
        }
    },
    [DataSourceType.NOTIFICATION_CHANNELS]: {
        url: '/api/v1/notification-channel/list',
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: `(${item.channelType})-${item.name}`,
                value: item.id
            }));
        }
    },
    [DataSourceType.K8S_CLUSTERS]: {
        url: '/api/v1/k8s-cluster/list',
        params: {enabled: true},
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: item.name,
                value: item.id,
                apiServer: item.apiServer
            }));
        }
    },
    [DataSourceType.GIT_REPOSITORIES]: {
        url: '/api/v1/git-repo/list',
        params: {enabled: true},
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: `${item.name} (${item.url})`,
                value: item.id,
                url: item.url
            }));
        }
    },
    [DataSourceType.DOCKER_REGISTRIES]: {
        url: '/api/v1/docker-registry/list',
        params: {enabled: true},
        transform: (data: any[]) => {
            return data.map((item: any) => ({
                label: item.name,
                value: item.id,
                url: item.url
            }));
        }
    }
};

/**
 * 加载数据源
 * @param type 数据源类型
 * @returns 选项列表
 */
export const loadDataSource = async (type: DataSourceType): Promise<DataSourceOption[]> => {
    const config = DATA_SOURCE_REGISTRY[type];

    if (!config) {
        console.error(`数据源类型 ${type} 未配置`);
        return [];
    }

    try {
        const response = await request.get(config.url, {params: config.params});
        // request 拦截器已经提取了 data 字段，response 直接是数组
        return config.transform(response || []);
    } catch (error) {
        console.error(`加载数据源 ${type} 失败:`, error);
        return [];
    }
};

/**
 * 批量加载多个数据源（用于预加载）
 * @param types 数据源类型列表
 * @returns 数据源数据映射
 */
export const loadMultipleDataSources = async (
    types: DataSourceType[]
): Promise<Record<DataSourceType, DataSourceOption[]>> => {
    const results = await Promise.all(
        types.map(type => loadDataSource(type))
    );

    return types.reduce((acc, type, index) => {
        acc[type] = results[index];
        return acc;
    }, {} as Record<DataSourceType, DataSourceOption[]>);
};

