/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { addDataSourceAsync as addDataSourceActionsAsync, getPlayerServiceConfig, } from '@microsoft/power-apps-actions';
import { getCliLogger, getSettings } from '../CliSettings.js';
import { createDefaultStringOption, promptConfirm, promptText } from '../CliUtils.js';
import { HelpStrings } from '../Constants/HelpStrings.js';
import { printInfo, printSuccess } from '../Utils/ConsoleOutput.js';
import { AddDataSourceArguments, SharedArguments } from './VerbConstants.js';
/**
 * Adds a data source based on the provided environment variables.
 * It supports both Dataverse and connector data sources.
 * Expects the following environment variables:
 * - API_ID: The ID of the API (e.g., 'dataverse' or a connector ID)
 * - CONNECTION_ID?: The ID of the connection (for connector data sources)
 * - TABLE?: The table name for Dataverse or tabular connector data sources
 * - ENV_URL?: The environment URL for Dataverse data sources
 * - DATASET?: The dataset name for tabular/stored proc connector data sources
 * - SQL_STORED_PROCEDURE?: The name of the SQL stored procedure for connector data sources
 * @param config - Local file paths configuration
 * @returns Promise<void>
 */
export async function addDataSourceAsync(argumentProvider) {
    const settings = getSettings();
    const { fileConfig, cliFs } = settings;
    createOptionSchema(argumentProvider);
    await argumentProvider.runVerb();
    const playerServiceConfig = getPlayerServiceConfig();
    // Use the already initialized authentication provider from ArgumentProvider
    const authenticationProvider = argumentProvider.getAuthenticationProvider();
    const dsConfig = {
        vfs: cliFs,
        authProvider: authenticationProvider,
        region: playerServiceConfig.region,
        environmentName: playerServiceConfig.environmentName,
        actionsParams: {
            apiId: () => argumentProvider.getOption('apiId'),
            connectionId: () => argumentProvider.getOption('connectionId'),
            tableName: () => argumentProvider.getOption('resourceName'),
            dataset: () => argumentProvider.getOption('dataset'),
            sqlStoredProcedure: () => argumentProvider.getOption('sqlStoredProcedure'),
            envUrl: () => argumentProvider.getOption('orgUrl'),
            solutionId: () => argumentProvider.getOption('solutionId'),
            connectionRef: () => argumentProvider.getOption('connectionRef'),
        },
        localFilePaths: {
            powerConfigPath: fileConfig.powerConfigPath,
            schemaPath: fileConfig.schemaPath,
            codeGenPath: fileConfig.codeGenPath,
        },
        logger: getCliLogger(),
    };
    await addDataSourceActionsAsync(dsConfig);
    printSuccess('Data source added successfully.');
    printInfo("Hint: Run 'npx power-apps run' to test locally, or 'npx power-apps push' to deploy.");
}
function createOptionSchema(argumentProvider) {
    argumentProvider.setDescription(HelpStrings.Verbs['Add-data-source'].Description);
    argumentProvider.addExamples(HelpStrings.Verbs['Add-data-source'].Examples);
    argumentProvider.addOptions([
        createDefaultStringOption({
            flags: {
                key: SharedArguments.ApiId.name,
                alias: SharedArguments.ApiId.alias,
            },
            env: SharedArguments.ApiId.envVar,
            message: SharedArguments.ApiId.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.ApiId,
        }),
        createDefaultStringOption({
            flags: {
                key: SharedArguments.ConnectionId.name,
                alias: SharedArguments.ConnectionId.alias,
            },
            env: SharedArguments.ConnectionId.envVar,
            message: SharedArguments.ConnectionId.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.ConnectionId,
        }),
        {
            flags: {
                key: AddDataSourceArguments.ConnectionRef.name,
                alias: AddDataSourceArguments.ConnectionRef.alias,
            },
            env: AddDataSourceArguments.ConnectionRef.envVar,
            description: HelpStrings.Verbs['Add-data-source'].Options.ConnectionRef,
            optionalInNonInteractive: true,
            customPrompt: async () => {
                const hasConnectionRef = await promptConfirm({
                    message: 'Are you using a connection reference instead of a connection ID?',
                });
                if (hasConnectionRef) {
                    return await promptText({
                        message: AddDataSourceArguments.ConnectionRef.promptMessage,
                    });
                }
                return '';
            },
        },
        createDefaultStringOption({
            flags: {
                key: SharedArguments.ResourceName.name,
                alias: SharedArguments.ResourceName.alias,
            },
            env: SharedArguments.ResourceName.envVar,
            message: SharedArguments.ResourceName.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.ResourceName,
        }),
        createDefaultStringOption({
            flags: {
                key: SharedArguments.Dataset.name,
                alias: SharedArguments.Dataset.alias,
            },
            env: SharedArguments.Dataset.envVar,
            message: SharedArguments.Dataset.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.Dataset,
        }),
        createDefaultStringOption({
            flags: {
                key: SharedArguments.OrgUrl.name,
                alias: SharedArguments.OrgUrl.alias,
            },
            env: SharedArguments.OrgUrl.envVar,
            message: SharedArguments.OrgUrl.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.OrgUrl,
        }),
        {
            flags: {
                key: SharedArguments.SqlStoredProcedure.name,
                alias: SharedArguments.SqlStoredProcedure.alias,
            },
            env: SharedArguments.SqlStoredProcedure.envVar,
            description: HelpStrings.Verbs['Add-data-source'].Options.SqlStoredProcedure,
            optionalInNonInteractive: true,
            customPrompt: async () => {
                const hasSqlProcedure = await promptConfirm({
                    message: 'Are you trying to add an SQL stored procedure?',
                });
                if (hasSqlProcedure) {
                    return await promptText({
                        message: SharedArguments.SqlStoredProcedure.promptMessage,
                    });
                }
                return '';
            },
        },
        createDefaultStringOption({
            flags: {
                key: SharedArguments.SolutionId.name,
                alias: SharedArguments.SolutionId.alias,
            },
            env: SharedArguments.SolutionId.envVar,
            message: SharedArguments.SolutionId.promptMessage,
            description: HelpStrings.Verbs['Add-data-source'].Options.SolutionId,
        }),
    ]);
}
//# sourceMappingURL=AddDataSource.js.map