const express = require("express");
const router = express.Router();
const db = require("../db");
const os = require("os");
const fs = require("fs");

// Get overall system health status
router.get("/status", async (req, res) => {
  try {
    // Check database connection
    let dbStatus = "disconnected";
    try {
      await db.execute("SELECT 1");
      dbStatus = "connected";
    } catch (error) {
      dbStatus = "disconnected";
    }

    // Check server status (basic health check)
    const serverStatus = "online";

    // Check network status (basic connectivity)
    const networkStatus = "stable";

    // Check security status (basic check)
    const securityStatus = "active";

    // Check storage status
    let storageStatus = "normal";
    try {
      const stats = fs.statSync(".");
      const freeSpace = os.freemem();
      const totalSpace = os.totalmem();
      const usagePercent = ((totalSpace - freeSpace) / totalSpace) * 100;

      if (usagePercent > 90) {
        storageStatus = "critical";
      } else if (usagePercent > 80) {
        storageStatus = "high";
      } else if (usagePercent > 70) {
        storageStatus = "medium";
      } else {
        storageStatus = "normal";
      }
    } catch (error) {
      storageStatus = "unknown";
    }

    // Check system load
    let systemLoad = "low";
    const loadAverage = os.loadavg();
    const avgLoad = (loadAverage[0] + loadAverage[1] + loadAverage[2]) / 3;

    if (avgLoad > 2.0) {
      systemLoad = "high";
    } else if (avgLoad > 1.0) {
      systemLoad = "medium";
    } else {
      systemLoad = "low";
    }

    // Get system metrics
    const systemMetrics = {
      uptime: Math.floor(os.uptime() / 3600), // hours
      memory: {
        total: Math.round(os.totalmem() / (1024 * 1024 * 1024)), // GB
        free: Math.round(os.freemem() / (1024 * 1024 * 1024)), // GB
        usage: Math.round(
          ((os.totalmem() - os.freemem()) / os.totalmem()) * 100
        ), // percentage
      },
      cpu: {
        cores: os.cpus().length,
        load: avgLoad.toFixed(2),
      },
      platform: os.platform(),
      arch: os.arch(),
    };

    const systemStatus = {
      server: serverStatus,
      database: dbStatus,
      network: networkStatus,
      security: securityStatus,
      storage: storageStatus,
      systemLoad: systemLoad,
      metrics: systemMetrics,
      lastUpdate: new Date().toISOString(),
    };

    res.json(systemStatus);
  } catch (error) {
    console.error("Error getting system health:", error);
    res.status(500).json({
      error: "Failed to get system health status",
      details: error.message,
    });
  }
});

// Get detailed database health
router.get("/database", async (req, res) => {
  try {
    // Check database connection
    const [result] = await db.execute("SELECT 1 as health_check");

    // Get database statistics
    const [tableCount] = await db.execute("SHOW TABLES");
    const [dbSize] = await db.execute(`
      SELECT 
        ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'size_mb'
      FROM information_schema.tables 
      WHERE table_schema = DATABASE()
    `);

    const dbHealth = {
      status: "connected",
      tables: tableCount.length,
      size_mb: dbSize[0]?.size_mb || 0,
      connection: "healthy",
      lastCheck: new Date().toISOString(),
    };

    res.json(dbHealth);
  } catch (error) {
    console.error("Error checking database health:", error);
    res.status(500).json({
      error: "Database health check failed",
      details: error.message,
    });
  }
});

// Get system performance metrics
router.get("/performance", async (req, res) => {
  try {
    const performance = {
      cpu: {
        load: os.loadavg(),
        cores: os.cpus().length,
        model: os.cpus()[0]?.model || "Unknown",
      },
      memory: {
        total: os.totalmem(),
        free: os.freemem(),
        used: os.totalmem() - os.freemem(),
        usagePercent: ((os.totalmem() - os.freemem()) / os.totalmem()) * 100,
      },
      uptime: os.uptime(),
      platform: os.platform(),
      arch: os.arch(),
      nodeVersion: process.version,
      timestamp: new Date().toISOString(),
    };

    res.json(performance);
  } catch (error) {
    console.error("Error getting performance metrics:", error);
    res.status(500).json({
      error: "Failed to get performance metrics",
      details: error.message,
    });
  }
});

// Health check endpoint for monitoring
router.get("/ping", (req, res) => {
  res.json({
    status: "healthy",
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
  });
});

module.exports = router;
