import { parse as parseUrl } from "url";
import EnvoyContext from "./envoy-context";
import EnvoyHttpRequestParams from "./envoy-http-request-params";
/**
 * to easier migrate from http request using request library, you can use this function
 * to refine the request params directly
 * @param params request params, can be url string or params object
 * @param ctx the context, can be EnvoyContext, grpc.Metadata or HttpHeader
 * @param init the extra options for the request
 */
export default function envoyRequestParamsRefiner(params, ctx, init) {
    if (!ctx) {
        return typeof params === "string" ? { url: params } : params;
    }
    let envoyContext;
    if (ctx instanceof EnvoyContext) {
        envoyContext = ctx;
    }
    else {
        envoyContext = new EnvoyContext(ctx);
    }
    const envoyParams = new EnvoyHttpRequestParams(envoyContext, init);
    let refinedParams;
    if (typeof params === "string") {
        refinedParams = { url: params };
    }
    else {
        refinedParams = Object.assign({}, params);
    }
    const refinedParamsWithUrl = refinedParams;
    const refinedParamsWithUri = refinedParams;
    if (Object.prototype.hasOwnProperty.call(refinedParams, "url")) {
        refinedParamsWithUri.uri = refinedParamsWithUrl.url;
        delete refinedParamsWithUrl.url;
    }
    if (!refinedParamsWithUri.uri) {
        throw new Error("Cannot read url from params");
    }
    if (typeof refinedParamsWithUri.uri === "string") {
        refinedParamsWithUri.uri = parseUrl(refinedParamsWithUri.uri);
    }
    const { protocol, host, path } = refinedParamsWithUri.uri;
    if (!protocol || !host || !path) {
        throw new Error("Cannot read the URL for envoy to fetch");
    }
    const callDirectly = envoyParams.context.shouldCallWithoutEnvoy(host);
    if (protocol !== "http:" && protocol !== "https:") {
        throw new Error(`envoy request is designed only for http / https for now, current found: ${protocol}`);
    }
    const oldHeaders = {};
    Object.assign(oldHeaders, refinedParamsWithUri.headers);
    refinedParamsWithUri.headers = Object.assign({}, oldHeaders, envoyParams.assembleRequestHeaders(), { host });
    if (!callDirectly) {
        refinedParamsWithUri.uri = `http://${envoyParams.context.envoyEgressAddr}:${envoyParams.context.envoyEgressPort}${path}`;
    }
    return refinedParams;
}
//# sourceMappingURL=envoy-request-params-refiner.js.map