import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'crypto';

declare module 'express' {
	interface Request {
		requestId?: string;
		traceId?: string;
		sessionId?: string;
	}
}

/**
 * Attaches a unique requestId to every incoming request.
 * Accepts X-Request-ID from trusted upstream proxies, otherwise generates a new UUID.
 * Also adds trace_id and session_id for audit tracing.
 */
export function requestIdMiddleware(req: Request, res: Response, next: NextFunction): void {
	const incoming = req.headers['x-request-id'];
	const requestId = typeof incoming === 'string' && /^[\w\-]{8,64}$/.test(incoming) ? incoming : randomUUID();

	// Add trace_id for workflow correlation
	const traceIncoming = req.headers['x-trace-id'];
	const traceId = typeof traceIncoming === 'string' ? traceIncoming : requestId;

	// Add session_id if available (will be set by auth middleware)
	const sessionId = (req as any).session?.id;

	req.requestId = requestId;
	req.traceId = traceId;
	req.sessionId = sessionId;

	res.setHeader('X-Request-ID', requestId);
	res.setHeader('X-Trace-ID', traceId);

	next();
}
