"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flexibleChecksumsResponseMiddleware = exports.flexibleChecksumsResponseMiddlewareOptions = void 0;
const protocol_http_1 = require("@smithy/protocol-http");
const isStreaming_1 = require("./isStreaming");
const create_read_stream_on_buffer_1 = require("./streams/create-read-stream-on-buffer");
const validateChecksumFromResponse_1 = require("./validateChecksumFromResponse");
exports.flexibleChecksumsResponseMiddlewareOptions = {
    name: "flexibleChecksumsResponseMiddleware",
    toMiddleware: "deserializerMiddleware",
    relation: "after",
    tags: ["BODY_CHECKSUM"],
    override: true,
};
const flexibleChecksumsResponseMiddleware = (config, middlewareConfig) => (next) => async (args) => {
    if (!protocol_http_1.HttpRequest.isInstance(args.request)) {
        return next(args);
    }
    const input = args.input;
    const result = await next(args);
    const response = result.response;
    let collectedStream = undefined;
    const { requestValidationModeMember, responseAlgorithms } = middlewareConfig;
    if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") {
        const isStreamingBody = (0, isStreaming_1.isStreaming)(response.body);
        if (isStreamingBody) {
            collectedStream = await config.streamCollector(response.body);
            response.body = (0, create_read_stream_on_buffer_1.createReadStreamOnBuffer)(collectedStream);
        }
        await (0, validateChecksumFromResponse_1.validateChecksumFromResponse)(result.response, {
            config,
            responseAlgorithms,
        });
        if (isStreamingBody && collectedStream) {
            response.body = (0, create_read_stream_on_buffer_1.createReadStreamOnBuffer)(collectedStream);
        }
    }
    return result;
};
exports.flexibleChecksumsResponseMiddleware = flexibleChecksumsResponseMiddleware;
