const { Pool } = require('pg');

// Try different possible DATABASE_URL formats for Supabase
const possibleUrls = [
  'postgresql://postgres.gzoclmbqmgmpuhufbnhy:postgres@aws-0-us-east-1.pooler.supabase.com:6543/postgres',
  'postgresql://postgres.gzoclmbqmgmpuhufbnhy:postgres@db.gzoclmbqmgmpuhufbnhy.supabase.co:5432/postgres',
  'postgresql://postgres:postgres@db.gzoclmbqmgmpuhufbnhy.supabase.co:5432/postgres'
];

async function testConnection(url, index) {
  console.log(`\n🔍 Testing connection ${index + 1}: ${url.replace(/:[^:@]*@/, ':****@')}`);
  
  const pool = new Pool({
    connectionString: url,
    max: 1,
    idleTimeoutMillis: 10000,
    connectionTimeoutMillis: 10000,
  });

  try {
    const client = await pool.connect();
    console.log(`✅ Connection ${index + 1} successful!`);
    
    // Test basic query
    const result = await client.query('SELECT NOW() as current_time');
    console.log(`✅ Query successful: ${result.rows[0].current_time}`);
    
    // Check if tables exist
    const tablesResult = await client.query(`
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      ORDER BY table_name
    `);
    
    console.log(`📋 Tables found: ${tablesResult.rows.length}`);
    if (tablesResult.rows.length > 0) {
      console.log('Tables:', tablesResult.rows.map(row => row.table_name).join(', '));
    }
    
    client.release();
    await pool.end();
    
    return { success: true, url, tables: tablesResult.rows };
    
  } catch (error) {
    console.log(`❌ Connection ${index + 1} failed: ${error.message}`);
    await pool.end();
    return { success: false, url, error: error.message };
  }
}

async function testAllConnections() {
  console.log('Testing production database connections...\n');
  
  const results = [];
  
  for (let i = 0; i < possibleUrls.length; i++) {
    const result = await testConnection(possibleUrls[i], i);
    results.push(result);
    
    if (result.success) {
      console.log(`\n🎉 Found working connection!`);
      console.log(`URL: ${result.url.replace(/:[^:@]*@/, ':****@')}`);
      return result;
    }
  }
  
  console.log('\n❌ All connection attempts failed');
  results.forEach((result, index) => {
    console.log(`Connection ${index + 1}: ${result.error}`);
  });
  
  return null;
}

testAllConnections(); 