/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
export class DataverseSystemDataService {
    httpClient;
    constructor(httpClient) {
        this.httpClient = httpClient;
    }
    async getEnvironmentVariables(orgUrl, logger) {
        const scenario = logger.trackScenario('GetEnvironmentVariables', {
            orgUrl,
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let additionalScenarioData = {};
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const selectParam = 'type,schemaname,displayname';
            const expandParam = 'environmentvariabledefinition_environmentvariablevalue($select=value)';
            const requestUri = `environmentvariabledefinitions` + `?$select=${selectParam}` + `&$expand=${expandParam}`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            additionalScenarioData = { url: fullUrl, authResource };
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            if (response.status === 200) {
                scenario.complete(additionalScenarioData);
            }
            else {
                additionalScenarioData.response = response.data;
                additionalScenarioData.status = response.status;
                scenario.completeWithError(additionalScenarioData);
            }
            return response?.data?.value;
        }
        catch (error) {
            scenario.failure({ error, ...additionalScenarioData });
            let errorMessage = `Failed to get environment variables from organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
    async getEnvironmentVariable(orgUrl, variableSchemaName, logger) {
        const scenario = logger.trackScenario('GetEnvironmentVariable', {
            orgUrl,
            variableSchemaName,
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let additionalScenarioData = {};
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const selectParam = 'type,schemaname,displayname';
            const expandParam = 'environmentvariabledefinition_environmentvariablevalue($select=value)';
            const requestUri = `environmentvariabledefinitions?$filter=schemaname%20eq%20%27${variableSchemaName}%27` +
                `&$select=${selectParam}` +
                `&$expand=${expandParam}`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            additionalScenarioData = { url: fullUrl, authResource };
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            if (response.status === 200) {
                scenario.complete(additionalScenarioData);
            }
            else {
                additionalScenarioData.response = response.data;
                additionalScenarioData.status = response.status;
                scenario.completeWithError(additionalScenarioData);
            }
            return response?.data?.value?.[0];
        }
        catch (error) {
            scenario.failure({ error, ...additionalScenarioData });
            let errorMessage = `Failed to get environment variable '${variableSchemaName}' from organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
    async getConnectionReferencesInSolution(solutionId, orgUrl, logger) {
        const scenario = logger.trackScenario('GetConnectionReferencesInSolution', {
            solutionId,
            orgUrl,
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let additionalScenarioData = {};
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const requestUri = `msdyn_solutioncomponentsummaries?$filter=(msdyn_solutionid eq ${solutionId}) and (msdyn_componentlogicalname eq 'connectionreference')&$orderby=msdyn_displayname asc&$select=msdyn_name,msdyn_displayname,msdyn_description`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            additionalScenarioData = { url: fullUrl, authResource };
            if (response.status === 200) {
                scenario.complete(additionalScenarioData);
            }
            else {
                additionalScenarioData.response = response.data;
                additionalScenarioData.status = response.status;
                scenario.completeWithError(additionalScenarioData);
            }
            return response?.data?.value || [];
        }
        catch (error) {
            scenario.failure({ error, ...additionalScenarioData });
            let errorMessage = `Failed to get connection references for solution '${solutionId}' in organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
    async getConnectionIdForReference(connectionReferenceLogicalName, orgUrl, logger) {
        const scenario = logger.trackScenario('GetConnectionIdForReference', {
            connectionReferenceLogicalName,
            orgUrl,
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let additionalScenarioData = {};
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const selectParam = `connectionreferenceid,connectionid,connectionreferencelogicalname`;
            const filterParam = `connectionreferencelogicalname eq '${connectionReferenceLogicalName}'`;
            const requestUri = `connectionreferences?$filter=${filterParam}&$select=${selectParam}`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            additionalScenarioData = { url: fullUrl, authResource };
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            if (response.status === 200) {
                scenario.complete(additionalScenarioData);
            }
            else {
                additionalScenarioData.response = response.data;
                additionalScenarioData.status = response.status;
                scenario.completeWithError(additionalScenarioData);
            }
            return response?.data?.value?.[0]?.connectionid;
        }
        catch (error) {
            scenario.failure({ error, ...additionalScenarioData });
            throw error;
        }
    }
    async getPreferredSolution(orgUrl) {
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const fullUrl = `${baseUrl}/api/data/v9.0/GetPreferredSolution`;
            const authResource = baseUrl + '/';
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            return response?.data?.solutionid;
        }
        catch (error) {
            let errorMessage = `Failed to get preferred solution from organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
    async getSolutions(orgUrl) {
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const selectParam = 'solutionid,uniquename,friendlyname,version,description,ismanaged';
            const requestUri = `solutions?$select=${selectParam}&$orderby=friendlyname asc`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong',
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            return response?.data?.value || [];
        }
        catch (error) {
            let errorMessage = `Failed to get solutions from organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
    /**
     * Retrieves all cloud flows (workflows with category = 5) from a Dataverse organization.
     * @param orgUrl The URL of the Dataverse organization.
     * @param logger The logger instance for tracking the scenario.
     * @param search Optional search term to filter flows by name (case-insensitive substring match).
     * @returns A promise that resolves to an array of DataverseWorkflow objects.
     * @throws An error if the HTTP request to the Dataverse API fails.
     */
    async getWorkflows(orgUrl, logger, search) {
        const scenario = logger.trackScenario('DataverseSystemDataService.GetWorkflows', {
            orgUrl,
            search,
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let additionalScenarioData = {};
        try {
            const baseUrl = orgUrl.endsWith('/') ? orgUrl.slice(0, -1) : orgUrl;
            const selectParam = 'workflowid,workflowidunique,solutionid,name,modifiedon,statecode,clientdata,resourceid';
            let filterParam = 'category eq 5'; // Category 5 represents cloud flows
            // Add name filter if search is provided
            if (search) {
                filterParam += ` and contains(name,'${search.replace(/'/g, "''")}')`;
            }
            const requestUri = `workflows?$filter=${encodeURIComponent(filterParam)}&$select=${selectParam}`;
            const fullUrl = `${baseUrl}/api/data/v9.0/${requestUri}`;
            const authResource = baseUrl + '/';
            additionalScenarioData = { url: fullUrl, authResource };
            const response = await this.httpClient.get(fullUrl, {
                authResource,
                headers: {
                    'User-Agent': 'PowerApps',
                    Consistency: 'Strong', // Force CDS to return latest metadata
                    Accept: 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                },
            });
            if (response.status === 200) {
                additionalScenarioData.resultCount = response.data.value.length;
                additionalScenarioData.hasNextLink = !!response.data['@odata.nextLink'];
                scenario.complete(additionalScenarioData);
            }
            else {
                additionalScenarioData.response = response.data;
                additionalScenarioData.status = response.status;
                scenario.completeWithError(additionalScenarioData);
            }
            return response?.data?.value || [];
        }
        catch (error) {
            scenario.failure({ error, ...additionalScenarioData });
            let errorMessage = `Failed to get workflows from organization '${orgUrl}'`;
            errorMessage += `: ${JSON.stringify(error)}`;
            throw new Error(errorMessage);
        }
    }
}
//# sourceMappingURL=DataverseSystemDataService.js.map