import { Request, Response, NextFunction } from 'express';
import { logger } from '@/infrastructure/monitoring/logger';

/**
 * dbis.edge.api-gateway
 * Terminates REST/gRPC-style requests, enforces authn/z, throttling, and correlation.
 */
export class GatewayApiService {
	/**
	 * Express middleware to inject/propagate correlation id.
	 */
	correlationMiddleware(req: Request, res: Response, next: NextFunction): void {
		const headerName = 'x-dbis-correlation-id';
		const correlationId =
			req.headers[headerName] ||
			req.headers['x-correlation-id'] ||
			`${Date.now()}-${Math.random().toString(36).slice(2)}`;
		res.setHeader(headerName, String(correlationId));
		(req as any).correlationId = correlationId;
		next();
	}

	/**
	 * Basic request size guard.
	 */
	sizeLimitGuard(maxBytes: number) {
		return (req: Request, res: Response, next: NextFunction) => {
			const contentLength = Number(req.headers['content-length'] || 0);
			if (contentLength > maxBytes) {
				logger.warn('Request rejected due to size limit', { contentLength, maxBytes });
				return res.status(413).json({ error: 'Payload Too Large' });
			}
			next();
		};
	}
}

export const gatewayApiService = new GatewayApiService();

