import { db } from "../server/db";
import { sql } from "drizzle-orm";

const GREEN = "\x1b[32m";
const RED = "\x1b[31m";
const YELLOW = "\x1b[33m";
const NC = "\x1b[0m";

async function healthCheck() {
  console.log("   Running AEGIS System Diagnostics...\n");

  const checks: { name: string; status: "PASS" | "WARN" | "FAIL"; details: string }[] = [];

  // Check 1: Database Connection
  try {
    await db.execute(sql`SELECT 1`);
    checks.push({ name: "PostgreSQL Connection", status: "PASS", details: "Connected to Neon DB" });
  } catch (error) {
    checks.push({ name: "PostgreSQL Connection", status: "FAIL", details: "Cannot connect to database" });
  }

  // Check 2: Users Table
  try {
    const result = await db.execute(sql`SELECT COUNT(*) as count FROM users`);
    const count = (result.rows[0] as any)?.count || 0;
    checks.push({ name: "Users Table", status: "PASS", details: `${count} users registered` });
  } catch (error) {
    checks.push({ name: "Users Table", status: "WARN", details: "Table not initialized" });
  }

  // Check 3: Threat Events Table
  try {
    const result = await db.execute(sql`SELECT COUNT(*) as count FROM threat_events`);
    const count = (result.rows[0] as any)?.count || 0;
    checks.push({ name: "Threat Events", status: "PASS", details: `${count} events recorded` });
  } catch (error) {
    checks.push({ name: "Threat Events", status: "WARN", details: "Table not initialized" });
  }

  // Check 4: Webhook Configs Table
  try {
    const result = await db.execute(sql`SELECT COUNT(*) as count FROM webhook_configs`);
    const count = (result.rows[0] as any)?.count || 0;
    checks.push({ name: "Webhook Integrations", status: "PASS", details: `${count} endpoints configured` });
  } catch (error) {
    checks.push({ name: "Webhook Integrations", status: "WARN", details: "Table not initialized" });
  }

  // Check 5: Audit Logs
  try {
    const result = await db.execute(sql`SELECT COUNT(*) as count FROM audit_logs`);
    const count = (result.rows[0] as any)?.count || 0;
    checks.push({ name: "Audit Logs (PDPO)", status: "PASS", details: `${count} entries logged` });
  } catch (error) {
    checks.push({ name: "Audit Logs (PDPO)", status: "WARN", details: "Table not initialized" });
  }

  // Check 6: Environment Variables
  const envChecks = [
    { key: "DATABASE_URL", required: true },
    { key: "SESSION_SECRET", required: false },
  ];

  for (const env of envChecks) {
    if (process.env[env.key]) {
      checks.push({ name: `ENV: ${env.key}`, status: "PASS", details: "Configured" });
    } else if (env.required) {
      checks.push({ name: `ENV: ${env.key}`, status: "FAIL", details: "Missing (required)" });
    } else {
      checks.push({ name: `ENV: ${env.key}`, status: "WARN", details: "Missing (optional)" });
    }
  }

  // Print Results
  console.log("   ┌─────────────────────────────────────────────────────────┐");
  console.log("   │             AEGIS CYBER HEALTH REPORT                   │");
  console.log("   ├────────────────────────────┬────────┬───────────────────┤");
  console.log("   │ Component                  │ Status │ Details           │");
  console.log("   ├────────────────────────────┼────────┼───────────────────┤");

  let hasFailed = false;
  for (const check of checks) {
    const statusColor = check.status === "PASS" ? GREEN : check.status === "WARN" ? YELLOW : RED;
    const name = check.name.padEnd(26);
    const status = check.status.padEnd(6);
    const details = check.details.slice(0, 17).padEnd(17);
    console.log(`   │ ${name} │ ${statusColor}${status}${NC} │ ${details} │`);
    if (check.status === "FAIL") hasFailed = true;
  }

  console.log("   └────────────────────────────┴────────┴───────────────────┘\n");

  if (hasFailed) {
    console.log(`   ${RED}System health check FAILED${NC}\n`);
    process.exit(1);
  } else {
    console.log(`   ${GREEN}All systems operational${NC}\n`);
    process.exit(0);
  }
}

healthCheck().catch((err) => {
  console.error("Health check error:", err);
  process.exit(1);
});
