/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { isOperationResult } from '../types';
import { HeaderNames } from './constants';
import { UnknownErrorMessage } from './messages';
import { PowerDataRuntimeError } from './types';
/**
 * Retrieves the error message from an error object.
 * @param error - The error to handle, which can be an instance of Error or IOperationResult.
 * @returns The error message if applicable, or throws the error if it's a PowerDataRuntimeError.
 * @private
 */
export function getErrorMessage(error) {
    if (typeof error === 'string') {
        return error;
    }
    if (error instanceof Error || error instanceof PowerDataRuntimeError) {
        return error.message || UnknownErrorMessage;
    }
    if (isOperationResult(error)) {
        return error.error?.message || UnknownErrorMessage;
    }
    if (typeof error === 'object') {
        return JSON.stringify(error);
    }
    return UnknownErrorMessage;
}
/**
 * Handles operation errors and creates an error OperationResult
 * @param error - The error object or OperationResult
 * @param friendlyMessage - A friendly message to include in the error
 * @private
 */
export function createErrorResponse(error, friendlyMessage) {
    const message = getErrorMessage(error);
    let data;
    if (isOperationResult(error)) {
        data = error.data;
    }
    const errorData = new Error(`${friendlyMessage}: ${message}`);
    if (error instanceof Error) {
        errorData.stack = error.stack;
    }
    return {
        success: false,
        error: errorData,
        data: data,
    };
}
/**
 * Parses an error from the HTTP plugin and returns a PowerDataRuntimeHttpError object.
 * @param error - The error to parse, which should be an array with a nested array.
 * @returns A PowerDataRuntimeHttpError object containing the message and response.
 * @private
 */
export function parseHttpPluginError(error) {
    let message = UnknownErrorMessage;
    let response;
    if (Array.isArray(error)) {
        if (Array.isArray(error[0])) {
            message = error[0][0] || UnknownErrorMessage;
            response = error[0][2];
        }
    }
    const status = response?.status;
    const requestId = response?.headers?.[HeaderNames.RequestId];
    return {
        message,
        status,
        requestId,
    };
}
//# sourceMappingURL=util.js.map