import { RequestOptions } from "@talentsoft-opensource/integration-widget-contract";
import { getSecurityMode } from "../securityModes/factory";
import { SecurityMode } from "../securityModes/securityMode";

const fetch = require("node-fetch");

async function formatResponse(response: Response) {
    const headers: Record<string, string> = {};
    response.headers.forEach((v, k) => {
        headers[k] = v;
    });
    return {
        status: response.status,
        headers: headers,
        body: await response.arrayBuffer()
    };
}

export async function downloadExternalResource(
    options: RequestOptions,
    secretKey: string,
    login: string,
    securityMode: SecurityMode
) {
    if (options.headers && options.headers.hasOwnProperty("host")) {
        delete options.headers["host"];
    }

    const securityModeImplementation = getSecurityMode(securityMode);
    const securityHeaders = securityModeImplementation.getSecurityHeaderParams(
        secretKey,
        login,
        new Date()
    );

    const response = await fetch(options.url, {
        headers: {
            ...options.headers,
            ...securityHeaders
        },
        method: options.verb,
        body: options.verb == "GET" ? undefined : options.body
    });

    return await formatResponse(response);
}
