/**
 * Quick Test Script untuk ISP Blocking Mitigation
 *
 * Jalankan script ini untuk test semua endpoint baru
 * Usage: node scripts/test-isp-mitigation.js
 */

const axios = require("axios");

// Configuration
const BASE_URL = process.env.BASE_URL || "http://localhost:4000";
const TEST_TOKEN = process.env.TEST_TOKEN || ""; // Optional: untuk test authenticated endpoints

// Color codes untuk console output
const colors = {
	reset: "\x1b[0m",
	green: "\x1b[32m",
	red: "\x1b[31m",
	yellow: "\x1b[33m",
	blue: "\x1b[34m",
	magenta: "\x1b[35m",
};

function log(message, color = "reset") {
	console.log(`${colors[color]}${message}${colors.reset}`);
}

function logSection(title) {
	console.log("\n" + "=".repeat(60));
	log(title, "blue");
	console.log("=".repeat(60) + "\n");
}

async function testEndpoint(name, url, method = "GET", data = null, headers = {}) {
	try {
		const startTime = Date.now();

		const response = await axios({
			method,
			url: `${BASE_URL}${url}`,
			data,
			headers,
			timeout: 10000,
		});

		const duration = Date.now() - startTime;

		log(`✓ ${name}`, "green");
		log(`  Status: ${response.status}`, "reset");
		log(`  Response Time: ${duration}ms`, "reset");

		// Show sample data (truncated)
		if (response.data) {
			const dataPreview = JSON.stringify(response.data, null, 2).substring(0, 200);
			log(`  Data: ${dataPreview}${JSON.stringify(response.data).length > 200 ? "..." : ""}`, "reset");
		}

		return { success: true, duration, status: response.status };
	} catch (error) {
		log(`✗ ${name}`, "red");
		log(`  Error: ${error.message}`, "red");

		if (error.response) {
			log(`  Status: ${error.response.status}`, "red");
			log(`  Message: ${error.response.data?.message || "N/A"}`, "red");
		}

		return { success: false, error: error.message };
	}
}

async function runTests() {
	log("Starting ISP Blocking Mitigation Tests", "magenta");
	log(`Base URL: ${BASE_URL}`, "yellow");
	log(`Timestamp: ${new Date().toISOString()}`, "yellow");

	const results = {
		total: 0,
		passed: 0,
		failed: 0,
		totalDuration: 0,
	};

	// Test 1: Health Check
	logSection("1. Health Check Endpoint");
	const healthResult = await testEndpoint("Health Check", "/health");
	results.total++;
	if (healthResult.success) {
		results.passed++;
		results.totalDuration += healthResult.duration;
	} else {
		results.failed++;
	}

	// Test 2: Ping
	logSection("2. Ping Endpoint");
	const pingResult = await testEndpoint("Ping Test", "/ping");
	results.total++;
	if (pingResult.success) {
		results.passed++;
		results.totalDuration += pingResult.duration;
	} else {
		results.failed++;
	}

	// Test 3: Diagnostics
	logSection("3. Connection Diagnostics");
	const diagResult = await testEndpoint("Diagnostics", "/diagnostics");
	results.total++;
	if (diagResult.success) {
		results.passed++;
		results.totalDuration += diagResult.duration;
	} else {
		results.failed++;
	}

	// Test 4: ISP Analytics (may require auth)
	logSection("4. ISP Analytics");
	const headers = TEST_TOKEN ? { Authorization: `Bearer ${TEST_TOKEN}` } : {};
	const analyticsResult = await testEndpoint("ISP Analytics", "/analytics/isp", "GET", null, headers);
	results.total++;
	if (analyticsResult.success) {
		results.passed++;
		results.totalDuration += analyticsResult.duration;
	} else {
		results.failed++;
		log("  Note: This endpoint might require authentication", "yellow");
	}

	// Test 5: CORS Preflight
	logSection("5. CORS Preflight Test");
	const corsResult = await testEndpoint("CORS Preflight", "/ping", "OPTIONS", null, {
		Origin: "https://sapps.sapharma.co.id",
		"Access-Control-Request-Method": "GET",
	});
	results.total++;
	if (corsResult.success) {
		results.passed++;
		results.totalDuration += corsResult.duration;
	} else {
		results.failed++;
	}

	// Test 6: Connection Resilience (simulate slow connection)
	logSection("6. Connection Timeout Test");
	log("Testing if server handles timeouts properly...", "yellow");
	try {
		const slowResult = await testEndpoint("Timeout Handling", "/ping", "GET", null, {}, 100); // Very short timeout
		results.total++;
		results.passed++;
	} catch (error) {
		results.total++;
		if (error.code === "ECONNABORTED") {
			log("✓ Server timeout handling works correctly", "green");
			results.passed++;
		} else {
			results.failed++;
		}
	}

	// Test 7: Static File Access
	logSection("7. Static File CORS Test");
	const staticResult = await testEndpoint("Static File Access", "/avatars/", "GET");
	results.total++;
	if (staticResult.success || staticResult.status === 403 || staticResult.status === 404) {
		// 403/404 is ok, means CORS headers are being sent
		results.passed++;
		log("  Note: 403/404 is expected if no files exist, but CORS headers should be present", "yellow");
	} else {
		results.failed++;
	}

	// Test 8: Multiple Rapid Requests (Rate Limit Test)
	logSection("8. Rate Limiting Test");
	log("Sending 10 rapid requests...", "yellow");
	let rateLimitPassed = 0;
	let rateLimitFailed = 0;

	for (let i = 0; i < 10; i++) {
		const result = await testEndpoint(`Request ${i + 1}/10`, "/ping", "GET");
		if (result.success) rateLimitPassed++;
		else rateLimitFailed++;
	}

	results.total++;
	if (rateLimitPassed >= 8) {
		// At least 80% should pass
		log(`✓ Rate limiting allows normal traffic (${rateLimitPassed}/10 passed)`, "green");
		results.passed++;
	} else {
		log(`✗ Rate limiting might be too strict (${rateLimitPassed}/10 passed)`, "red");
		results.failed++;
	}

	// Summary
	logSection("Test Summary");
	log(`Total Tests: ${results.total}`, "blue");
	log(`Passed: ${results.passed}`, "green");
	log(`Failed: ${results.failed}`, results.failed > 0 ? "red" : "green");

	if (results.passed > 0) {
		const avgDuration = Math.round(results.totalDuration / results.passed);
		log(`Average Response Time: ${avgDuration}ms`, "yellow");

		// Connection quality assessment
		let quality = "Excellent";
		if (avgDuration > 1000) quality = "Poor";
		else if (avgDuration > 500) quality = "Fair";
		else if (avgDuration > 200) quality = "Good";

		log(`Connection Quality: ${quality}`, avgDuration > 500 ? "yellow" : "green");
	}

	// Final verdict
	console.log("\n" + "=".repeat(60));
	if (results.failed === 0) {
		log("🎉 All tests passed! ISP mitigation is working correctly.", "green");
	} else if (results.passed > results.failed) {
		log("⚠️  Some tests failed, but core functionality is working.", "yellow");
	} else {
		log("❌ Multiple tests failed. Please check server configuration.", "red");
	}
	console.log("=".repeat(60) + "\n");

	// Recommendations
	if (results.failed > 0) {
		log("Recommendations:", "magenta");
		log("1. Check if server is running: " + BASE_URL, "yellow");
		log("2. Verify CORS configuration in app.js", "yellow");
		log("3. Check firewall/network settings", "yellow");
		log("4. Review logs/isp-blocking-alerts.log for details", "yellow");
	}

	process.exit(results.failed > 0 ? 1 : 0);
}

// Run tests
runTests().catch((error) => {
	log(`Fatal error: ${error.message}`, "red");
	console.error(error);
	process.exit(1);
});
