/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { getSanitizedUniqueName } from '../CodeGen/shared/nameUtils.js';
/**
 * Upserts a database reference in the provided collection.
 * @param databaseReferences - The collection of database references.
 * @param params - Parameters for the database reference.
 * @param params.entitySetName - The name of the entity set.
 * @param params.logicalName - The logical name of the entity.
 * @param params.environmentName - The name of the environment (optional).
 * @param params.cdpDataSourceNames - The names of the CDP data sources (optional).
 * @returns The disambiguated data source name.
 */
export function upsertDatabaseReference(databaseReferences, params) {
    const { entitySetName, logicalName, cdpDataSourceNames, displayName } = params;
    // TODO: Support environment variables and cross-environment references
    const dbRefKey = 'default.cds';
    const existingDbRef = databaseReferences[dbRefKey];
    // Check if a data source with the same logicalName already exists — if so, update it in-place
    // to avoid creating duplicates when the same table is added or refreshed more than once.
    if (existingDbRef?.dataSources) {
        const existingEntry = Object.entries(existingDbRef.dataSources).find(([, ds]) => ds.logicalName === logicalName);
        if (existingEntry) {
            const [existingKey, existingDataSource] = existingEntry;
            existingDbRef.dataSources[existingKey] = {
                entitySetName,
                logicalName,
                isHidden: existingDataSource.isHidden,
            };
            return existingKey;
        }
    }
    const allExistingNames = [
        ...(cdpDataSourceNames ?? []),
        ...getExistingDataverseNames(databaseReferences),
    ];
    const dataSourceName = getSanitizedUniqueName(allExistingNames, displayName);
    if (existingDbRef) {
        if (!existingDbRef.dataSources) {
            existingDbRef.dataSources = {};
        }
        existingDbRef.dataSources[dataSourceName] = {
            entitySetName,
            logicalName,
            isHidden: false,
        };
    }
    else {
        databaseReferences[dbRefKey] = {
            dataSources: {
                [dataSourceName]: {
                    entitySetName,
                    logicalName,
                    isHidden: false,
                },
            },
            environmentVariableName: '',
        };
    }
    return dataSourceName;
}
export function getExistingDataverseNames(databaseReferences) {
    return Object.values(databaseReferences).reduce((acc, dbRef) => acc.concat(Object.keys(dbRef.dataSources || {})), []);
}
//# sourceMappingURL=databaseReferences.js.map