#!/usr/bin/env node

/**
 * Environment Validation Script
 * Checks if all dependencies and database are properly configured
 */

const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
require('dotenv').config();

const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
};

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

async function validateEnvironment() {
  console.log('\n' + '='.repeat(60));
  log('🔍 Numerology CMS Backend - Environment Validation', 'blue');
  console.log('='.repeat(60) + '\n');

  let hasErrors = false;

  // 1. Check Node.js version
  log('Checking Node.js version...', 'blue');
  const nodeVersion = process.version;
  const majorVersion = parseInt(nodeVersion.split('.')[0].substring(1));
  if (majorVersion >= 14) {
    log(`✓ Node.js ${nodeVersion}`, 'green');
  } else {
    log(`✗ Node.js ${nodeVersion} - Requires v14+`, 'red');
    hasErrors = true;
  }

  // 2. Check .env file
  log('\nChecking .env file...', 'blue');
  if (fs.existsSync(path.join(__dirname, '.env'))) {
    log('✓ .env file exists', 'green');
  } else {
    log('✗ .env file not found', 'red');
    log('  → Copy .env.example to .env', 'yellow');
    hasErrors = true;
  }

  // 3. Check node_modules
  log('\nChecking dependencies...', 'blue');
  if (fs.existsSync(path.join(__dirname, 'node_modules'))) {
    log('✓ node_modules directory exists', 'green');
  } else {
    log('✗ node_modules not found', 'red');
    log('  → Run: npm install', 'yellow');
    hasErrors = true;
  }

  // 4. Check required files
  log('\nChecking required files...', 'blue');
  const requiredFiles = [
    'server.js',
    'package.json',
    'config/database.js',
    'controllers/adminController.js',
    'controllers/userController.js',
    'models/Admin.js',
    'models/User.js',
    'routes/adminRoutes.js',
    'routes/userRoutes.js',
    'middleware/verifyAccessToken.js',
    'middleware/verifyRole.js',
    'utils/tokenUtils.js',
    'utils/passwordUtils.js',
  ];

  let missingFiles = [];
  requiredFiles.forEach((file) => {
    if (fs.existsSync(path.join(__dirname, file))) {
      log(`✓ ${file}`, 'green');
    } else {
      log(`✗ ${file} missing`, 'red');
      missingFiles.push(file);
    }
  });

  if (missingFiles.length > 0) {
    hasErrors = true;
  }

  // 5. Check environment variables
  log('\nChecking environment variables...', 'blue');
  const requiredEnvVars = [
    'PORT',
    'NODE_ENV',
    'DB_HOST',
    'DB_PORT',
    'DB_USER',
    'DB_PASSWORD',
    'DB_NAME',
    'JWT_SECRET',
    'JWT_REFRESH_SECRET',
  ];

  requiredEnvVars.forEach((envVar) => {
    if (process.env[envVar]) {
      log(`✓ ${envVar}`, 'green');
    } else {
      log(`✗ ${envVar} not set`, 'red');
      hasErrors = true;
    }
  });

  // 6. Test database connection
  log('\nTesting database connection...', 'blue');
  try {
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
    });

    await connection.ping();
    log(`✓ MySQL connection successful (${process.env.DB_HOST}:${process.env.DB_PORT})`, 'green');

    // Check tables
    const [tables] = await connection.execute(
      "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?",
      [process.env.DB_NAME]
    );

    if (tables.length > 0) {
      log(`✓ Database tables found: ${tables.map(t => t.TABLE_NAME).join(', ')}`, 'green');
    } else {
      log('✗ No tables found in database', 'red');
      log('  → Run: mysql -u root -p numerology_master < database.sql', 'yellow');
      hasErrors = true;
    }

    await connection.end();
  } catch (error) {
    log(`✗ Database connection failed: ${error.message}`, 'red');
    log('  → Ensure MySQL is running and credentials are correct', 'yellow');
    hasErrors = true;
  }

  // 7. Summary
  console.log('\n' + '='.repeat(60));
  if (!hasErrors) {
    log('✓ All checks passed! Server is ready to run.', 'green');
    log('\nStart the server with:', 'blue');
    log('  npm run dev    (development with auto-reload)', 'yellow');
    log('  npm start      (production mode)', 'yellow');
  } else {
    log('✗ Please fix the errors above before running the server.', 'red');
    process.exit(1);
  }
  console.log('='.repeat(60) + '\n');
}

validateEnvironment().catch((error) => {
  log(`Fatal error: ${error.message}`, 'red');
  process.exit(1);
});
