import { getLogger as getLogger$1 } from "../logger.js";
import { sentry } from "../sentry.js";
import { handleApiError } from "@inkeep/agents-core";
import { HTTPException } from "hono/http-exception";

//#region src/middleware/errorHandler.ts
const logger = getLogger$1("error-handler");
/**
* Extract Zod validation issues from an error object
*/
function extractZodIssues(err) {
	if (err && typeof err === "object") {
		if ("cause" in err && err.cause && typeof err.cause === "object" && "issues" in err.cause) {
			const issues = err.cause.issues;
			if (Array.isArray(issues)) return issues;
		}
		if ("issues" in err && Array.isArray(err.issues)) return err.issues;
	}
}
/**
* Format Zod validation errors into RFC 7807 problem detail format
*/
function formatZodValidationError(c, zodIssues) {
	c.status(400);
	c.header("Content-Type", "application/problem+json");
	return c.json({
		type: "https://docs.inkeep.com/agents-api/errors#bad_request",
		title: "Validation Failed",
		status: 400,
		detail: "Request validation failed",
		errors: zodIssues.map((issue) => ({
			detail: issue.message,
			pointer: issue.path ? `/${issue.path.join("/")}` : void 0,
			name: issue.path ? issue.path.join(".") : void 0,
			reason: issue.message
		}))
	});
}
/**
* Log server errors with appropriate context
*/
function logServerError(err, path, requestId, status, isExpectedError) {
	if (!isExpectedError) {
		const errorMessage = err instanceof Error ? err.message : String(err);
		const errorStack = err instanceof Error ? err.stack : void 0;
		logger.error({
			error: err,
			message: errorMessage,
			stack: errorStack,
			path,
			requestId
		}, "Unexpected server error occurred");
	} else logger.error({
		error: err,
		path,
		requestId,
		status
	}, "Server error occurred");
}
/**
* Global error handler for the Hono application
* Handles Zod validation errors, HTTP exceptions, and unexpected errors
* Returns RFC 7807 Problem Details format
*/
async function errorHandler(err, c) {
	const isExpectedError = err instanceof HTTPException;
	const status = isExpectedError ? err.status : 500;
	const requestId = c.get("requestId") || "unknown";
	const zodIssues = extractZodIssues(err);
	if (status === 400 && zodIssues) return formatZodValidationError(c, zodIssues);
	if (status >= 500) {
		logServerError(err, c.req.path, requestId, status, isExpectedError);
		sentry.captureException(err, { extra: {
			requestId,
			path: c.req.path,
			status
		} });
	}
	const errorResponse = await handleApiError(err, requestId);
	c.status(errorResponse.status);
	const { code, title, status: responseStatus, detail, instance, requestId: _reqId, error: errorObj, ...extensions } = errorResponse;
	const responseBody = {
		...code && { code },
		title,
		status: responseStatus,
		detail,
		...instance && { instance },
		...errorObj && { error: errorObj },
		...extensions
	};
	c.header("Content-Type", "application/problem+json");
	return c.body(JSON.stringify(responseBody));
}

//#endregion
export { errorHandler };