#!/usr/bin/env node

// Production Readiness Test Script
// Tests critical functionality before deployment

const fs = require('fs');
const path = require('path');

console.log('\n🧪 WakaTraffic Production Readiness Tests');
console.log('==========================================\n');

let testsRun = 0;
let testsPassed = 0;
let testsFailed = 0;
const issues = [];

// Test 1: Check .env file exists
testsRun++;
console.log('1. Checking .env file...');
if (fs.existsSync('.env')) {
  console.log('   ✅ .env file exists');
  testsPassed++;
} else {
  console.log('   ❌ .env file missing');
  issues.push('.env file not found - copy from .env.example');
  testsFailed++;
}

// Test 2: Check .gitignore exists
testsRun++;
console.log('2. Checking .gitignore...');
if (fs.existsSync('.gitignore')) {
  console.log('   ✅ .gitignore exists');
  testsPassed++;
} else {
  console.log('   ❌ .gitignore missing');
  issues.push('.gitignore file not found');
  testsFailed++;
}

// Test 3: Check server.js exists
testsRun++;
console.log('3. Checking server.js...');
if (fs.existsSync('server.js')) {
  console.log('   ✅ server.js exists');
  testsPassed++;
} else {
  console.log('   ❌ server.js missing');
  issues.push('server.js file not found');
  testsFailed++;
}

// Test 4: Check node_modules exists
testsRun++;
console.log('4. Checking dependencies...');
if (fs.existsSync('node_modules')) {
  console.log('   ✅ node_modules found (dependencies installed)');
  testsPassed++;
} else {
  console.log('   ⚠️  node_modules missing - run: npm install');
  issues.push('Dependencies not installed - run npm install');
  testsFailed++;
}

// Test 5: Check database directory
testsRun++;
console.log('5. Checking database files...');
if (fs.existsSync('database/schema.sql')) {
  console.log('   ✅ Database schema file exists');
  testsPassed++;
} else {
  console.log('   ❌ database/schema.sql missing');
  issues.push('Database schema file not found');
  testsFailed++;
}

// Test 6: Check routes directory
testsRun++;
console.log('6. Checking routes directory...');
const requiredRoutes = [
  'routes/adminDashboardRoutes.js',
  'routes/adminUserRoutes.js',
  'routes/adminOrderRoutes.js',
  'routes/depositRoutes.js'
];
let routesExist = true;
requiredRoutes.forEach(route => {
  if (!fs.existsSync(route)) {
    console.log(`   ❌ Missing: ${route}`);
    routesExist = false;
  }
});
if (routesExist) {
  console.log('   ✅ All required route files exist');
  testsPassed++;
} else {
  issues.push('Some route files are missing');
  testsFailed++;
}

// Test 7: Check services directory
testsRun++;
console.log('7. Checking services directory...');
const requiredServices = [
  'services/EmailService.js',
  'services/OwletService.js',
  'services/DashboardService.js'
];
let servicesExist = true;
requiredServices.forEach(service => {
  if (!fs.existsSync(service)) {
    console.log(`   ❌ Missing: ${service}`);
    servicesExist = false;
  }
});
if (servicesExist) {
  console.log('   ✅ All required service files exist');
  testsPassed++;
} else {
  issues.push('Some service files are missing');
  testsFailed++;
}

// Test 8: Check middleware
testsRun++;
console.log('8. Checking middleware...');
if (fs.existsSync('middleware/authMiddleware.js')) {
  console.log('   ✅ Auth middleware exists');
  testsPassed++;
} else {
  console.log('   ❌ Auth middleware missing');
  issues.push('middleware/authMiddleware.js not found');
  testsFailed++;
}

// Test 9: Check public directory
testsRun++;
console.log('9. Checking public directory...');
if (fs.existsSync('public') && fs.existsSync('public/index.html')) {
  console.log('   ✅ Public directory exists');
  testsPassed++;
} else {
  console.log('   ⚠️  Public directory or index.html missing');
  issues.push('Public directory not properly configured');
  testsFailed++;
}

// Test 10: Check environment configuration
testsRun++;
console.log('10. Checking environment variables...');
if (fs.existsSync('.env')) {
  const envContent = fs.readFileSync('.env', 'utf8');
  const requiredVars = ['DB_HOST', 'DB_NAME', 'JWT_SECRET', 'SMTP_HOST', 'ADMIN_EMAIL'];
  let allVarsPresent = true;

  requiredVars.forEach(varName => {
    if (!envContent.includes(varName + '=')) {
      console.log(`   ⚠️  Missing environment variable: ${varName}`);
      allVarsPresent = false;
    }
  });

  // Check for weak secrets
  if (envContent.includes('your-super-secret-jwt-key-change-this-in-production')) {
    console.log('   ⚠️  Using default JWT secret - CHANGE IMMEDIATELY');
    issues.push('Default JWT secret detected - generate strong secret');
    allVarsPresent = false;
  }

  if (allVarsPresent) {
    console.log('   ✅ All required environment variables present');
    testsPassed++;
  } else {
    console.log('   ⚠️  Some environment variables need attention');
    testsFailed++;
  }
} else {
  console.log('   ❌ .env file not found');
  testsFailed++;
}

// Test 11: Check documentation
testsRun++;
console.log('11. Checking documentation...');
const docs = ['README.md', 'NAMECHEAP_DEPLOYMENT.md'];
let docsExist = true;
docs.forEach(doc => {
  if (!fs.existsSync(doc)) {
    console.log(`   ❌ Missing: ${doc}`);
    docsExist = false;
  }
});
if (docsExist) {
  console.log('   ✅ Essential documentation exists');
  testsPassed++;
} else {
  issues.push('Some documentation files are missing');
  testsFailed++;
}

// Test 12: Check for old/duplicate files
testsRun++;
console.log('12. Checking for old duplicate files...');
const oldFiles = ['backend-server.js', 'server-mysql.js', 'test-owlet.js'];
let hasOldFiles = false;
oldFiles.forEach(file => {
  if (fs.existsSync(file)) {
    console.log(`   ⚠️  Old file found: ${file}`);
    hasOldFiles = true;
  }
});
if (!hasOldFiles) {
  console.log('   ✅ No old duplicate files found');
  testsPassed++;
} else {
  console.log('   ⚠️  Old files detected - run cleanup.sh');
  testsFailed++;
}

// Summary
console.log('\n==========================================');
console.log('📊 Test Summary');
console.log('==========================================');
console.log(`Total Tests: ${testsRun}`);
console.log(`✅ Passed: ${testsPassed}`);
console.log(`❌ Failed: ${testsFailed}`);
console.log(`Success Rate: ${Math.round((testsPassed / testsRun) * 100)}%`);

if (issues.length > 0) {
  console.log('\n⚠️  Issues Found:\n');
  issues.forEach((issue, index) => {
    console.log(`${index + 1}. ${issue}`);
  });
}

console.log('\n==========================================');

if (testsFailed === 0) {
  console.log('✅ ALL TESTS PASSED! Ready for deployment.');
  console.log('\n📝 Next Steps:');
  console.log('1. Review .env file and update production values');
  console.log('2. Generate strong secrets (see .env.example)');
  console.log('3. Configure email SMTP settings');
  console.log('4. Follow NAMECHEAP_DEPLOYMENT.md guide');
  process.exit(0);
} else {
  console.log('⚠️  SOME TESTS FAILED - Fix issues before deployment');
  console.log('\n📝 Required Actions:');
  console.log('1. Fix all ❌ failed tests above');
  console.log('2. Run this test again: node scripts/test-production-readiness.js');
  console.log('3. Once all tests pass, proceed with deployment');
  process.exit(1);
}
