/**
 * Quick Setup Script for IP Tracking System
 * Run: node setup-ip-tracking.js
 */

const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");

console.log("🚀 IP Tracking & Connection Monitoring Setup");
console.log("=".repeat(60));

// Step 1: Check dependencies
console.log("\n📦 Step 1: Checking dependencies...");
try {
	const packageJson = require("../package.json");
	const deps = packageJson.dependencies || {};

	if (!deps["geoip-lite"]) {
		console.log("  ⚠️  geoip-lite not found in package.json");
		console.log("  📥 Installing geoip-lite...");
		execSync("npm install geoip-lite --save", { stdio: "inherit" });
		console.log("  ✅ geoip-lite installed");
	} else {
		console.log("  ✅ geoip-lite already installed");
	}
} catch (error) {
	console.error("  ❌ Error checking dependencies:", error.message);
	process.exit(1);
}

// Step 2: Check if tables exist
console.log("\n🗄️  Step 2: Checking database tables...");
console.log("  ℹ️  Please run migration manually:");
console.log("  📝 Command: npx sequelize-cli db:migrate");
console.log("  📝 Or create tables manually from migrations/007-create-connection-tracking.js");

// Step 3: Check if models exist
console.log("\n🏗️  Step 3: Checking models...");
const modelsPath = path.join(__dirname, "apps/sapps/helpers/models");
const requiredModels = ["connection_attempts.js", "isp_statistics.js", "blocked_ips.js"];
let allModelsExist = true;

requiredModels.forEach((model) => {
	const modelPath = path.join(modelsPath, model);
	if (fs.existsSync(modelPath)) {
		console.log(`  ✅ ${model} exists`);
	} else {
		console.log(`  ❌ ${model} NOT FOUND`);
		allModelsExist = false;
	}
});

if (!allModelsExist) {
	console.log("  ⚠️  Some models are missing. Please create them from IMPLEMENTATION_GUIDE.md");
}

// Step 4: Check middleware
console.log("\n🔌 Step 4: Checking middleware...");
const middlewarePath = path.join(__dirname, "middlewares/connection-tracker.js");
if (fs.existsSync(middlewarePath)) {
	console.log("  ✅ connection-tracker.js exists");
} else {
	console.log("  ❌ connection-tracker.js NOT FOUND");
}

// Step 5: Check utilities
console.log("\n🛠️  Step 5: Checking utilities...");
const utilPath = path.join(__dirname, "utils/ispDetector.js");
if (fs.existsSync(utilPath)) {
	console.log("  ✅ ispDetector.js exists");
} else {
	console.log("  ❌ ispDetector.js NOT FOUND");
}

// Step 6: Check API routes
console.log("\n🌐 Step 6: Checking API routes...");
const routesPath = path.join(__dirname, "apps/analytics/ip-analytics.routes.js");
const servicePath = path.join(__dirname, "apps/analytics/ip-analytics.service.js");
if (fs.existsSync(routesPath)) {
	console.log("  ✅ ip-analytics.routes.js exists");
} else {
	console.log("  ❌ ip-analytics.routes.js NOT FOUND");
}
if (fs.existsSync(servicePath)) {
	console.log("  ✅ ip-analytics.service.js exists");
} else {
	console.log("  ❌ ip-analytics.service.js NOT FOUND");
}

// Step 7: Check app.js integration
console.log("\n📝 Step 7: Checking app.js integration...");
const appJsPath = path.join(__dirname, "app.js");
const appJsContent = fs.readFileSync(appJsPath, "utf8");

const checks = [
	{
		name: "connection-tracker require",
		pattern: /require.*connection-tracker/,
		found: false,
	},
	{
		name: "connection-tracker middleware",
		pattern: /app\.use\(connectionTracker\)/,
		found: false,
	},
	{
		name: "ip-analytics routes",
		pattern: /ip-analytics\.routes/,
		found: false,
	},
];

checks.forEach((check) => {
	check.found = check.pattern.test(appJsContent);
	if (check.found) {
		console.log(`  ✅ ${check.name} - integrated`);
	} else {
		console.log(`  ⚠️  ${check.name} - NOT FOUND in app.js`);
	}
});

// Summary
console.log("\n" + "=".repeat(60));
console.log("📊 Setup Summary:");
console.log("=".repeat(60));

let setupComplete = allModelsExist && fs.existsSync(middlewarePath) && fs.existsSync(utilPath) && fs.existsSync(routesPath) && fs.existsSync(servicePath);

if (setupComplete && checks.every((c) => c.found)) {
	console.log("\n✅ All files are in place and integrated!");
	console.log("\n📋 Next Steps:");
	console.log("  1. Run database migration:");
	console.log("     npx sequelize-cli db:migrate");
	console.log("  2. Restart your server:");
	console.log("     npm start");
	console.log("  3. Test the endpoints:");
	console.log("     curl http://localhost:4000/api/ip-analytics/summary");
	console.log("  4. Access dashboard:");
	console.log("     http://localhost:4000/public/dashboard.html");
	console.log("\n📚 Documentation:");
	console.log("  - IMPLEMENTATION_GUIDE.md - Step-by-step setup");
	console.log("  - IP_TRACKING_README.md - Full system documentation");
	console.log("  - .analysis/IP_TRACKING_ANALYSIS.md - Technical analysis");
} else {
	console.log("\n⚠️  Setup is INCOMPLETE. Missing components:");
	if (!allModelsExist) console.log("  - Database models");
	if (!fs.existsSync(middlewarePath)) console.log("  - Middleware (connection-tracker.js)");
	if (!fs.existsSync(utilPath)) console.log("  - Utility (ispDetector.js)");
	if (!fs.existsSync(routesPath) || !fs.existsSync(servicePath)) console.log("  - API routes/service");
	if (!checks.every((c) => c.found)) console.log("  - app.js integration");

	console.log("\n📖 Please follow IMPLEMENTATION_GUIDE.md for complete setup");
}

console.log("\n" + "=".repeat(60));
console.log("🎉 Setup check complete!");
console.log("=".repeat(60) + "\n");
