const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
const require_errors = require('../../types/errors.cjs');
const require_user_agent = require('../../user_agent.cjs');
const require_utils = require('./utils.cjs');
let node_buffer = require("node:buffer");
node_buffer = require_rolldown_runtime.__toESM(node_buffer);
let node_zlib = require("node:zlib");
node_zlib = require_rolldown_runtime.__toESM(node_zlib);

//#region src/endpoint/handlers/lambda.ts
const RESPONSE_COMPRESSION_THRESHOLD = 3 * 1024 * 1024;
var LambdaHandler = class {
	constructor(handler, compressionSupported) {
		this.handler = handler;
		this.compressionSupported = compressionSupported;
	}
	async handleRequest(event, context) {
		const abortController = new AbortController();
		try {
			const path = "path" in event ? event.path : event.rawPath;
			let requestContentEncoding;
			let requestAcceptEncoding;
			for (const [key, value] of Object.entries(event.headers)) if (key.localeCompare("content-encoding", void 0, { sensitivity: "accent" }) === 0) requestContentEncoding = value;
			else if (key.localeCompare("accept-encoding", void 0, { sensitivity: "accent" }) === 0) requestAcceptEncoding = value;
			let inputReader;
			if (!event.body) inputReader = require_utils.emptyInputReader();
			else {
				let bodyBuffer;
				if (event.isBase64Encoded) bodyBuffer = node_buffer.Buffer.from(event.body, "base64");
				else bodyBuffer = node_buffer.Buffer.from(new TextEncoder().encode(event.body));
				if (requestContentEncoding && requestContentEncoding.includes("zstd")) {
					if (!this.compressionSupported) throw new Error("The input is compressed using zstd, but this lambda deployment doesn't support compression. Make sure to deploy the Lambda using Node > 22");
					bodyBuffer = node_zlib.zstdDecompressSync(bodyBuffer);
				}
				inputReader = (async function* () {
					yield bodyBuffer;
				})()[Symbol.asyncIterator]();
			}
			const chunks = [];
			const outputWriter = {
				write: function(value) {
					chunks.push(value);
					return Promise.resolve();
				},
				close: function() {
					return Promise.resolve();
				}
			};
			const response = this.handler.handle({
				headers: event.headers,
				url: path,
				extraArgs: [context]
			}, { AWSRequestId: context.awsRequestId });
			try {
				await response.process({
					inputReader,
					outputWriter,
					abortSignal: abortController.signal
				});
			} catch (e) {
				const error = require_errors.ensureError(e);
				(require_utils.tryCreateContextualLogger(this.handler.endpoint.loggerTransport, path, event.headers) ?? this.handler.endpoint.rlog).error("Unexpected error: " + (error.stack ?? error.message));
				return {
					headers: {
						"content-type": "application/json",
						"x-restate-server": require_user_agent.X_RESTATE_SERVER
					},
					statusCode: 500,
					isBase64Encoded: false,
					body: JSON.stringify({ message: error.message })
				};
			}
			const responseBodyBuffer = node_buffer.Buffer.concat(chunks);
			let responseBody;
			if (this.compressionSupported && responseBodyBuffer.length > RESPONSE_COMPRESSION_THRESHOLD && requestAcceptEncoding && requestAcceptEncoding.includes("zstd")) {
				response.headers["content-encoding"] = "zstd";
				responseBody = node_zlib.zstdCompressSync(responseBodyBuffer).toString("base64");
			} else responseBody = responseBodyBuffer.toString("base64");
			return {
				headers: response.headers,
				statusCode: response.statusCode,
				isBase64Encoded: true,
				body: responseBody
			};
		} finally {
			abortController.abort();
		}
	}
};
function isCompressionSupported() {
	return "zstdDecompressSync" in node_zlib && "zstdCompressSync" in node_zlib;
}

//#endregion
exports.LambdaHandler = LambdaHandler;
exports.isCompressionSupported = isCompressionSupported;