/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { processDataSourceInfo } from '../CodeGen/dataSourceInfoProcessor.js';
import { clearAndRegenerateModelService, generateModelService, } from '../CodeGen/modelServiceGenerator.js';
import { getAllJsonFiles } from '../CodeGen/shared/schemaUtils.js';
import { readRepoConfig } from '../Config/ConfigManager.js';
import { getVfs, setVfs } from '../VfsManager.js';
/**
 * Collects all data source names from power.config.json.
 */
function collectAllDataSourceNames(repoConfig) {
    const names = [];
    if (repoConfig.databaseReferences) {
        for (const dbRef of Object.values(repoConfig.databaseReferences)) {
            for (const dsName of Object.keys(dbRef.dataSources)) {
                names.push(dsName);
            }
        }
    }
    if (repoConfig.connectionReferences) {
        for (const connRef of Object.values(repoConfig.connectionReferences)) {
            if (connRef.dataSets && Object.keys(connRef.dataSets).length > 0) {
                for (const dataSet of Object.values(connRef.dataSets)) {
                    for (const dsName of Object.keys(dataSet.dataSources)) {
                        names.push(dsName);
                    }
                }
            }
            else if (connRef.dataSources) {
                for (const ds of connRef.dataSources) {
                    names.push(ds);
                }
            }
        }
    }
    return names;
}
/**
 * Finds schema files matching a data source name.
 * Schema files are named {dsName}.Schema.json (case-insensitive match on dsName).
 */
async function findSchemaFilesForDataSource(schemaFolderPath, dataSourceName) {
    const vfs = getVfs();
    const allJsonFiles = await getAllJsonFiles(schemaFolderPath);
    const lowerName = dataSourceName.toLowerCase();
    return allJsonFiles.filter((filePath) => {
        const fileName = vfs.basename(filePath).toLowerCase();
        return fileName === `${lowerName}.schema.json`;
    });
}
/**
 * Regenerates TypeScript code for data sources from existing schema files.
 * Does not re-fetch schemas from the API — uses the local .Schema.json files already on disk.
 *
 * If `config.actionsParams.dataSource` is specified, only that data source is regenerated.
 * If the name does not match any known data source, an error is thrown.
 *
 * @param config - Context including VFS, file paths, and optional data source name filter.
 * @returns A result object with `succeeded` and `failed` arrays.
 */
export async function regenDataSourceTsAsync(config) {
    setVfs(config.vfs);
    const vfs = getVfs();
    const { powerConfigPath, schemaPath, codeGenPath } = config.localFilePaths;
    const { logger } = config;
    if (!(await vfs.exists(powerConfigPath))) {
        throw new Error(`Configuration file not found at ${powerConfigPath}`);
    }
    const repoConfig = await readRepoConfig(powerConfigPath);
    const allDataSourceNames = collectAllDataSourceNames(repoConfig);
    const targetDataSource = config.actionsParams.dataSource;
    if (targetDataSource) {
        const exists = allDataSourceNames.some((name) => name.toLowerCase() === targetDataSource.toLowerCase());
        if (!exists) {
            throw new Error(`'${targetDataSource}' is not a valid data source name. ` +
                `Available data sources: ${allDataSourceNames.join(', ')}`);
        }
    }
    const succeeded = [];
    const failed = [];
    try {
        await processDataSourceInfo(schemaPath, logger);
        if (targetDataSource) {
            const schemaFiles = await findSchemaFilesForDataSource(schemaPath, targetDataSource);
            if (schemaFiles.length === 0) {
                throw new Error(`No schema file found for data source '${targetDataSource}'. ` +
                    `Expected a file named '${targetDataSource}.Schema.json' under '${schemaPath}'.`);
            }
            for (const schemaFile of schemaFiles) {
                await generateModelService({
                    schemaFolderPath: schemaPath,
                    schemaFilePath: schemaFile,
                    codeGenPath,
                    logger,
                });
            }
            succeeded.push(targetDataSource);
        }
        else {
            await clearAndRegenerateModelService({
                schemaFolderPath: schemaPath,
                codeGenPath,
                logger,
            });
            succeeded.push(...allDataSourceNames);
        }
    }
    catch (err) {
        const dsName = targetDataSource ?? 'all';
        failed.push({
            dataSourceName: dsName,
            error: err instanceof Error ? err.message : String(err),
        });
    }
    return { succeeded, failed };
}
//# sourceMappingURL=RegenDataSourceTs.js.map