import { ensureError } from "../../types/errors.js";
import { X_RESTATE_SERVER } from "../../user_agent.js";
import { errorResponse } from "./utils.js";

//#region src/endpoint/handlers/preview.ts
function handlePreview(endpoint, previewPathComponent) {
	const service = endpoint.components.get(previewPathComponent.componentName);
	if (!service) {
		const msg = `No service found for name: ${previewPathComponent.componentName}`;
		endpoint.rlog.error(msg);
		return errorResponse(404, msg);
	}
	const resolvedSerde = service.serdeMatching(previewPathComponent.serdeName);
	if (!resolvedSerde?.preview) {
		const msg = `No previewable serde found for URL: ${JSON.stringify(previewPathComponent)}`;
		endpoint.rlog.error(msg);
		return errorResponse(404, msg);
	}
	return new RestatePreviewResponse(resolvedSerde, previewPathComponent.operation);
}
var RestatePreviewResponse = class {
	constructor(serde, operation) {
		this.serde = serde;
		this.operation = operation;
	}
	async process({ inputReader, outputWriter, writeHead }) {
		const response = await this.computeResponse(inputReader);
		writeHead(response.statusCode, response.headers);
		try {
			await outputWriter.write(response.body);
		} finally {
			await outputWriter.close();
		}
	}
	async computeResponse(inputReader) {
		try {
			const body = await readAllInput(inputReader);
			return this.operation === "decode" ? await this.decode(body) : await this.encode(body);
		} catch (e) {
			return previewErrorResponse(ensureError(e).message);
		}
	}
	async decode(requestBody) {
		const value = this.serde.deserialize(requestBody);
		const json = await this.serde.preview.toJsonString(value);
		return {
			statusCode: 200,
			headers: {
				"content-type": "application/json",
				"x-restate-server": X_RESTATE_SERVER
			},
			body: new TextEncoder().encode(json)
		};
	}
	async encode(requestBody) {
		const json = new TextDecoder().decode(requestBody);
		const value = await this.serde.preview.fromJsonString(json);
		return {
			statusCode: 200,
			headers: {
				"content-type": this.serde.contentType ?? "application/octet-stream",
				"x-restate-server": X_RESTATE_SERVER
			},
			body: this.serde.serialize(value)
		};
	}
};
function previewErrorResponse(message) {
	return {
		statusCode: 422,
		headers: {
			"content-type": "application/json",
			"x-restate-server": X_RESTATE_SERVER
		},
		body: new TextEncoder().encode(JSON.stringify({ message }))
	};
}
async function readAllInput(inputReader) {
	const chunks = [];
	let totalLength = 0;
	while (true) {
		const chunk = await inputReader.next();
		if (chunk.done) break;
		chunks.push(chunk.value);
		totalLength += chunk.value.length;
	}
	const combined = new Uint8Array(totalLength);
	let offset = 0;
	for (const chunk of chunks) {
		combined.set(chunk, offset);
		offset += chunk.length;
	}
	return combined;
}

//#endregion
export { handlePreview };
//# sourceMappingURL=preview.js.map