import { isObject } from '@redocly/theme/core/openapi';
export function updateOperationWithRequestValues(operation, userDefinedRequestValues) {
    if (Object.keys(userDefinedRequestValues).length === 0)
        return;
    if (isDirectRequestValues(userDefinedRequestValues)) {
        updateRequestBodyWithUserValues(operation, userDefinedRequestValues);
        updateSecurityWithUserValues(operation, userDefinedRequestValues.security);
        updateEnvVariablesWithUserValues(operation, userDefinedRequestValues.envVariables);
    }
    else {
        const serverRequestValues = userDefinedRequestValues;
        updateOperationWithServerUserValues(operation, serverRequestValues);
    }
}
export function updateParametersWithUserValues(param, userDefinedRequestValues) {
    if (!userDefinedRequestValues)
        return;
    const { in: paramIn, name: paramName } = param;
    if (isDirectRequestValues(userDefinedRequestValues)) {
        const requestValues = userDefinedRequestValues;
        const paramSources = {
            header: requestValues.headers,
            query: requestValues.query,
            path: requestValues.path,
            cookie: requestValues.cookie,
        };
        if (paramIn && paramSources[paramIn]?.[paramName]) {
            param.example = paramSources[paramIn][paramName];
        }
    }
    else {
        Object.entries(userDefinedRequestValues).forEach(([serverUrl, requestValues]) => {
            const serverRequestValues = requestValues;
            if (!serverRequestValues)
                return;
            const paramSources = {
                header: serverRequestValues.headers,
                query: serverRequestValues.query,
                path: serverRequestValues.path,
                cookie: serverRequestValues.cookie,
            };
            if (paramIn && paramSources[paramIn]?.[paramName]) {
                if (!param.serverValues) {
                    param.serverValues = {};
                }
                param.serverValues[serverUrl] = {
                    example: paramSources[paramIn][paramName],
                };
            }
        });
    }
}
export function updateRequestBodyWithUserValues(operation, userDefinedRequestValues, serverUrl) {
    if (!operation.requestBody || !userDefinedRequestValues?.body)
        return;
    const content = operation.requestBody.content;
    if (!content?.mediaTypes)
        return;
    const processExamples = (mediaType, examplesKey) => {
        if (!mediaType[examplesKey])
            return;
        Object.keys(mediaType[examplesKey]).forEach((exampleKey) => {
            const currentValue = mediaType[examplesKey]?.[exampleKey]?.value;
            let newValue;
            if (isObject(currentValue)) {
                newValue = updateObjectProperties(currentValue, userDefinedRequestValues.body);
            }
            else {
                newValue = userDefinedRequestValues.body;
            }
            if (!newValue) {
                return;
            }
            // If server URL is provided, store the value in the server-specific 'serverValues' field
            if (serverUrl) {
                const existingExample = mediaType[examplesKey][exampleKey];
                if (!existingExample.serverValues) {
                    existingExample.serverValues = {};
                }
                existingExample.serverValues[serverUrl] = {
                    value: newValue,
                    rawValue: newValue,
                };
                mediaType[examplesKey][exampleKey] = {
                    ...existingExample,
                    mime: mediaType.name,
                };
            }
            else {
                mediaType[examplesKey][exampleKey] = {
                    value: newValue,
                    rawValue: newValue,
                    mime: mediaType.name,
                };
            }
        });
    };
    for (const mediaType of content.mediaTypes) {
        processExamples(mediaType, 'examples');
        processExamples(mediaType, 'formExamples');
    }
    return operation;
}
export function updateSecurityWithUserValues(operation, securityValues, serverUrl) {
    if (!securityValues || !operation.security.length)
        return;
    operation.security.forEach((securityRequirement) => {
        if (serverUrl) {
            securityRequirement.schemes.forEach((scheme) => {
                if (!scheme.serverValues) {
                    scheme.serverValues = {};
                }
                const credentials = createSecurityUpdates(scheme, securityValues);
                scheme.serverValues[serverUrl] = credentials;
            });
        }
        else {
            securityRequirement.schemes.forEach((scheme) => {
                const updates = createSecurityUpdates(scheme, securityValues);
                Object.assign(scheme, updates);
            });
        }
    });
}
export function updateOperationWithServerUserValues(operation, serverRequestValues) {
    operation.servers.forEach((server) => {
        if (serverRequestValues[server.url]) {
            const userDefinedRequestValues = serverRequestValues[server.url];
            if (userDefinedRequestValues) {
                updateRequestBodyWithUserValues(operation, userDefinedRequestValues, server.url);
                updateSecurityWithUserValues(operation, userDefinedRequestValues.security, server.url);
                updateEnvVariablesWithUserValues(operation, userDefinedRequestValues.envVariables, server.url);
            }
        }
    });
}
export function updateEnvVariablesWithUserValues(operation, environmentValues, serverUrl) {
    if (!environmentValues || Object.keys(environmentValues).length === 0)
        return;
    if (!operation.envVariables) {
        operation.envVariables = {};
    }
    if (serverUrl) {
        if (!operation.envVariables.serverValues) {
            operation.envVariables.serverValues = {};
        }
        operation.envVariables.serverValues[serverUrl] = {
            ...operation.envVariables.serverValues[serverUrl],
            ...environmentValues,
        };
    }
    else {
        operation.envVariables.values = {
            ...operation.envVariables.values,
            ...environmentValues,
        };
    }
}
export function isDirectRequestValues(value) {
    if (!value || typeof value !== 'object')
        return false;
    return ('headers' in value ||
        'body' in value ||
        'query' in value ||
        'path' in value ||
        'cookie' in value ||
        'security' in value ||
        'envVariables' in value);
}
export function updateObjectProperties(original, updates) {
    if (!original || typeof original !== 'object') {
        return updates;
    }
    if (Array.isArray(original) && Array.isArray(updates)) {
        if (original.length > 0 && typeof original[0] === 'object' && original[0] !== null) {
            const originalKeys = Object.keys(original[0]);
            const filteredUpdates = updates.filter((updateItem) => {
                if (typeof updateItem !== 'object' || updateItem === null)
                    return false;
                return (originalKeys.some((key) => key in updateItem) &&
                    Object.keys(updateItem).every((key) => originalKeys.includes(key)));
            });
            return filteredUpdates.length > 0 ? filteredUpdates : original;
        }
        return updates;
    }
    const result = Array.isArray(original) ? [...original] : { ...original };
    for (const [key, value] of Object.entries(updates)) {
        if (key in original) {
            if (Array.isArray(original[key])) {
                result[key] = updateObjectProperties(original[key], value);
            }
            else if (typeof value === 'object' && value !== null && typeof original[key] === 'object') {
                result[key] = updateObjectProperties(original[key], value);
            }
            else {
                result[key] = value;
            }
        }
    }
    return result;
}
export function createSecurityUpdates(scheme, securityValues) {
    const updates = {
        'x-defaultAccessToken': securityValues.token?.access_token,
        'x-defaultTokenType': securityValues.token?.token_type || 'Bearer',
        'x-defaultClientId': securityValues.client_id,
        'x-defaultClientSecret': securityValues.client_secret,
        scopes: securityValues.scopes || scheme.scopes,
    };
    if (scheme.type === 'http' && scheme.scheme === 'basic') {
        updates['x-defaultUsername'] = securityValues.username;
        updates['x-defaultPassword'] = securityValues.password;
        delete updates['x-defaultAccessToken'];
        delete updates['x-defaultTokenType'];
    }
    else if (scheme.type === 'oauth2' && !securityValues.token?.access_token) {
        delete updates['x-defaultAccessToken'];
        delete updates['x-defaultTokenType'];
    }
    return updates;
}
//# sourceMappingURL=configure-helpers.js.map