#!/usr/bin/env node
/**
 * Database Health Check Script
 * Tests database connectivity and performance
 * Usage: node scripts/db-health.js
 */

const db = require("../config/database");
const logger = require("../config/logger");

async function runHealthCheck() {
  console.log("🔍 Running database health check...\n");

  try {
    // Run health check with timeout
    const result = await db.healthCheck(5000);

    if (result.healthy) {
      console.log("✅ DATABASE HEALTHY");
      console.log("━━━━━━━━━━━━━━━━━━━━━━");
      console.log(`Database: ${result.database}`);
      console.log(`Timestamp: ${result.timestamp}`);
      console.log(`\nConnection Pool:`);
      console.log(`  Total Connections: ${result.pool.total}`);
      console.log(`  Idle Connections:  ${result.pool.idle}`);
      console.log(`  Waiting Requests:  ${result.pool.waiting}`);
      console.log(`  Pool Connected:    ${result.pool.connected ? "✓" : "✗"}`);
      console.log(`\nQuery Cache:`);
      console.log(
        `  Cached Queries: ${result.cache.size}/${result.cache.maxSize}`
      );
      console.log(
        `  Usage: ${((result.cache.size / result.cache.maxSize) * 100).toFixed(
          1
        )}%`
      );

      // Get additional pool status
      const poolStatus = db.getPoolStatus();
      console.log(`\n📊 Pool Status: OPERATIONAL`);

      process.exitCode = 0;
    } else {
      console.log("❌ DATABASE UNHEALTHY");
      console.log("━━━━━━━━━━━━━━━━━━━━━━");
      console.log(`Error: ${result.error}`);
      if (result.pool) {
        console.log(`\nPool State:`);
        console.log(
          `  Total: ${result.pool.total}, Idle: ${result.pool.idle}, Waiting: ${result.pool.waiting}`
        );
      }
      process.exitCode = 1;
    }
  } catch (error) {
    console.log("💥 HEALTH CHECK FAILED");
    console.log("━━━━━━━━━━━━━━━━━━━━━━");
    console.log(`Error: ${error.message}`);
    console.log(`\nThis usually indicates:`);
    console.log(`  1. Database connection timeout`);
    console.log(`  2. PostgreSQL service not running`);
    console.log(`  3. Network/firewall issues`);
    console.log(`  4. Database credentials incorrect`);
    process.exitCode = 1;
  } finally {
    // Gracefully close the pool
    console.log("\n🔌 Closing database connections...");
    await db.closePool();
    console.log("✓ Database pool closed\n");
  }
}

// Run the check
runHealthCheck().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
