import { getErrorMeta, getLogger } from "../util/logger.js";
const isPromise = (value) => {
    return value instanceof Promise;
};
/**
 * Wraps a method with error handling that emits an error event when an exception occurs
 * NOTE: This swallows the error
 *
 * @param instance - The object instance containing the method to wrap
 * @param methodName - The name of the method to wrap
 */
export function withErrorHandling(instance, methodName, details) {
    const originalMethod = instance[methodName];
    if (typeof originalMethod !== "function")
        return;
    const handleError = (error) => {
        const logger = getLogger();
        const name = error instanceof Error ? error.name : "Unknown error";
        logger.error(name, getErrorMeta(error));
        const errorEvent = {
            type: "server/edit-operation",
            timestamp: new Date().toISOString(),
            operation: details.operation,
            name,
            message: error instanceof Error
                ? error.message
                : `Unknown error in ${methodName}`,
            stackTrace: error instanceof Error ? error.stack : undefined,
        };
        instance.emit("error", errorEvent);
        if (details.rethrow) {
            throw error;
        }
    };
    instance[methodName] = function (...args) {
        try {
            const result = originalMethod.apply(this, args);
            if (isPromise(result)) {
                return result.catch(handleError);
            }
            else {
                return result;
            }
        }
        catch (error) {
            handleError(error);
        }
    };
}
/**
 * Helper function to apply error handling to multiple methods at once
 *
 * @param instance - The object instance containing the methods to wrap
 * @param methods - Record of method names to wrap with error handling
 */
export function applyErrorHandling(instance, methods) {
    for (const [methodName, details] of Object.entries(methods)) {
        const finalDetails = {
            ...details,
            rethrow: details.rethrow ?? false,
        };
        withErrorHandling(instance, methodName, finalDetails);
    }
}
//# sourceMappingURL=error-handler.js.map