"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateChecksumFromResponse = void 0;
const getChecksum_1 = require("./getChecksum");
const getChecksumAlgorithmListForResponse_1 = require("./getChecksumAlgorithmListForResponse");
const getChecksumLocationName_1 = require("./getChecksumLocationName");
const selectChecksumAlgorithmFunction_1 = require("./selectChecksumAlgorithmFunction");
const validateChecksumFromResponse = async (response, { config, responseAlgorithms }) => {
    const checksumAlgorithms = (0, getChecksumAlgorithmListForResponse_1.getChecksumAlgorithmListForResponse)(responseAlgorithms);
    const { body: responseBody, headers: responseHeaders } = response;
    for (const algorithm of checksumAlgorithms) {
        const responseHeader = (0, getChecksumLocationName_1.getChecksumLocationName)(algorithm);
        const checksumFromResponse = responseHeaders[responseHeader];
        if (checksumFromResponse) {
            const checksumAlgorithmFn = (0, selectChecksumAlgorithmFunction_1.selectChecksumAlgorithmFunction)(algorithm, config);
            const { streamHasher, base64Encoder } = config;
            const checksum = await (0, getChecksum_1.getChecksum)(responseBody, { streamHasher, checksumAlgorithmFn, base64Encoder });
            if (checksum === checksumFromResponse) {
                break;
            }
            throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}"` +
                ` in response header "${responseHeader}".`);
        }
    }
};
exports.validateChecksumFromResponse = validateChecksumFromResponse;
