import { NextFunction } from 'express';
import { Req, Res } from '#interfaces/IApi';
import { GenericError } from '#interfaces/error/generic';

/**
 * Error Context Middleware
 *
 * Injects requestId and userId into error context for better debugging and tracing.
 * This middleware should be placed before the response middleware in the middleware chain.
 */
export function errorContextMiddleware(_req: Req, _res: Res, next: NextFunction): void {
	const originalError = _res.error;

	// Override res.error to inject context
	_res.error = function (err: unknown) {
		if (err instanceof GenericError) {
			// Inject request context
			err.requestId = (_req as any).requestId;
			err.userId = (_req as any).user?.id;
		}
		return originalError.call(this, err);
	};

	next();
}
