"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOperationData = void 0;
const lodash_1 = require("lodash");
const openapi_sampler_1 = require("openapi-sampler");
function getOperationData(operation) {
    const queryParams = getParamsFromOperation(operation, 'query');
    const headerParams = getParamsFromOperation(operation, 'headers');
    let auth;
    for (const security of lodash_1.flatten(operation.security)) {
        const schema = {
            type: 'string',
            description: security.description,
        };
        if (security.type === 'http' && security.scheme === 'bearer') {
            headerParams.push({
                name: 'authorization',
                value: 'Bearer',
                isEnabled: true,
                schema,
                required: true,
            });
        }
        else if (security.type === 'http' && security.scheme === 'basic') {
            auth = { username: '', password: '' };
        }
        else if ('in' in security) {
            const param = {
                name: security.name,
                value: '',
                isEnabled: true,
                schema,
                required: true,
            };
            if (security.in === 'query') {
                queryParams.push(param);
            }
            else if (security.in === 'header') {
                headerParams.push(param);
            }
        }
    }
    const body = getBodyFromOperation(operation) || '';
    return {
        publicServers: operation.servers || [],
        publicBaseUrl: lodash_1.get(operation, 'servers[0].url', ''),
        method: operation.method || 'get',
        templatedPath: operation.path || '',
        body,
        contentType: body ? 'raw' : 'none',
        pathParams: getParamsFromOperation(operation, 'path'),
        queryParams,
        headerParams,
        auth,
    };
}
exports.getOperationData = getOperationData;
function getParamsFromOperation(operation, type) {
    return lodash_1.filter(lodash_1.get(operation, `request.${type}`, []), p => lodash_1.get(p, 'name')).map((p) => (Object.assign(Object.assign({ name: p.name, value: lodash_1.has(p.schema, 'default') ? String(lodash_1.get(p.schema, 'default')) : '', isEnabled: p.required || lodash_1.has(p.schema, 'default') }, (p.required && { required: p.required })), (p.schema && { schema: p.schema }))));
}
function getBodyFromOperation(operation) {
    try {
        const schema = lodash_1.get(operation, 'request.body.contents[0].schema');
        if (schema) {
            return openapi_sampler_1.sample(schema, {}, operation);
        }
    }
    catch (e) {
        console.warn('Unable to create sample request body from schema', e);
        return undefined;
    }
    return undefined;
}
//# sourceMappingURL=getOperationData.js.map