import 'dotenv/config';
import mongoose from 'mongoose';
import dns from 'dns';
import { promisify } from 'util';

const resolveTxt = promisify(dns.resolveTxt);
const resolve4 = promisify(dns.resolve4);

async function testConnection() {
  console.log('🔍 Testing MongoDB Connection...\n');

  // Check if MONGO_URI exists
  if (!process.env.MONGO_URI) {
    console.error('❌ MONGO_URI not found in environment variables');
    process.exit(1);
  }

  // Extract hostname from URI
  const uriMatch = process.env.MONGO_URI.match(/@([^/]+)/);
  const hostname = uriMatch ? uriMatch[1].split('?')[0] : null;

  console.log('📋 Connection Details:');
  console.log(`   URI: ${process.env.MONGO_URI.replace(/mongodb\+srv:\/\/([^:]+):([^@]+)@/, 'mongodb+srv://$1:****@')}`);
  console.log(`   Hostname: ${hostname}\n`);

  // Test DNS resolution
  if (hostname) {
    console.log('🌐 Testing DNS Resolution...');
    
    try {
      console.log('   Testing DNS TXT records...');
      const txtRecords = await resolveTxt(hostname);
      console.log('   ✅ DNS TXT resolution successful');
      console.log(`   Records: ${JSON.stringify(txtRecords)}\n`);
    } catch (error) {
      console.error(`   ❌ DNS TXT resolution failed: ${error.message}`);
      console.log('   💡 This might be a DNS or network issue\n');
    }

    try {
      console.log('   Testing DNS A records (IPv4)...');
      const addresses = await resolve4(hostname);
      console.log('   ✅ DNS A resolution successful');
      console.log(`   IP Addresses: ${addresses.join(', ')}\n`);
    } catch (error) {
      console.error(`   ❌ DNS A resolution failed: ${error.message}\n`);
    }
  }

  // Test MongoDB connection
  console.log('🔌 Attempting MongoDB Connection...');
  
  const connectionOptions = {
    retryWrites: true,
    w: 'majority',
  };

  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, connectionOptions);
    console.log('✅ MongoDB Connected Successfully!');
    console.log(`   Host: ${conn.connection.host}`);
    console.log(`   Database: ${conn.connection.name}`);
    console.log(`   Port: ${conn.connection.port}\n`);

    // Close connection
    await mongoose.connection.close();
    console.log('✅ Connection closed gracefully');
    process.exit(0);
  } catch (error) {
    console.error('❌ MongoDB Connection Failed!');
    console.error(`   Error Code: ${error.code}`);
    console.error(`   Error Message: ${error.message}\n`);

    console.log('💡 Troubleshooting Tips:');
    console.log('   1. Check your internet connection');
    console.log('   2. Verify MongoDB Atlas IP whitelist (should include 0.0.0.0/0 for testing)');
    console.log('   3. Check if your network/firewall blocks MongoDB Atlas');
    console.log('   4. Try using MongoDB connection string with +srv removed (direct connection)');
    console.log('   5. Check MongoDB Atlas cluster status at https://cloud.mongodb.com\n');

    process.exit(1);
  }
}

testConnection();
