/**
 * Performance Optimizer Middleware
 * Applies request/response optimizations without breaking existing functionality
 * Safe for backward compatibility
 */

const config = require("../config.json");

/**
 * Apply performance optimizations to the Express app
 * This middleware enhances performance without changing existing behavior
 */
function applyPerformanceOptimizations(app) {
	// 1. Optimize request timeout (reducing from 120s to 30s for faster failure detection)
	const requestTimeout = config.backendConfig?.requestTimeout || 30000;
	app.use((req, res, next) => {
		// Set reasonable timeout
		req.setTimeout(requestTimeout, () => {
			console.warn(`[Performance] Request timeout for ${req.method} ${req.path}`);
		});
		res.setTimeout(requestTimeout);
		next();
	});

	// 2. Add response time header for monitoring
	app.use((req, res, next) => {
		const startTime = Date.now();

		// Remove X-Powered-By for security
		res.removeHeader("X-Powered-Info");

		// Add timing header
		res.on("finish", () => {
			const duration = Date.now() - startTime;
			res.setHeader("X-Response-Time", `${duration}ms`);

			// Log slow requests (>3s)
			if (duration > 3000) {
				console.warn(`[Performance] Slow request: ${req.method} ${req.path} took ${duration}ms`);
			}
		});

		next();
	});

	// 3. Optimize JSON parsing for better performance
	app.use((req, res, next) => {
		// Add content-type validation
		if (req.method === "POST" || req.method === "PUT") {
			const contentType = req.headers["content-type"];
			if (contentType && !contentType.includes("application/json") && !contentType.includes("multipart/form-data")) {
				console.warn(`[Performance] Unexpected content-type: ${contentType} for ${req.method} ${req.path}`);
			}
		}
		next();
	});

	// 4. Connection pooling info middleware (for monitoring)
	app.use(async (req, res, next) => {
		// Only add occasionally to reduce overhead
		if (Math.random() < 0.01) {
			// 1% of requests
			try {
				const dbSAPPS = require("../apps/sapps/helpers/db");
				if (dbSAPPS.dbConnectionManager) {
					const stats = dbSAPPS.dbConnectionManager.getConnectionStats();
					// Add to request for potential debugging
					req._dbStats = stats;
				}
			} catch (e) {
				// Silently ignore - this is just for monitoring
			}
		}
		next();
	});

	// 5. Optimize cache headers for static assets
	app.use((req, res, next) => {
		const staticExtensions = [".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".woff", ".woff2", ".ttf"];
		const ext = req.path.split(".").pop();

		if (staticExtensions.includes(`.${ext}`)) {
			// Static assets can be cached longer
			res.setHeader("Cache-Control", "public, max-age=86400"); // 24 hours
		}

		next();
	});

	console.log(`[Performance] Optimizations applied (timeout: ${requestTimeout}ms)`);
}

/**
 * Get performance statistics
 */
function getPerformanceStats() {
	const mem = process.memoryUsage();
	const cpu = process.cpuUsage();

	return {
		memory: {
			heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + " MB",
			heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + " MB",
			rss: Math.round(mem.rss / 1024 / 1024) + " MB",
			external: Math.round(mem.external / 1024 / 1024) + " MB",
		},
		cpu: {
			user: cpu.user,
			system: cpu.system,
		},
		uptime: process.uptime(),
		pid: process.pid,
	};
}

module.exports = {
	applyPerformanceOptimizations,
	getPerformanceStats,
};
