const mysql = require('mysql2/promise');
const { Client } = require('ssh2');
const dotenv = require('dotenv');
const path = require('path');

dotenv.config({ path: path.join(__dirname, '../.env') });

// SSH configuration
const sshConfig = {
  host: process.env.PROD_SSH_HOST,
  port: process.env.PROD_SSH_PORT || 22,
  username: process.env.PROD_SSH_USER,
  privateKey: process.env.PROD_SSH_KEY_PATH ? require('fs').readFileSync(process.env.PROD_SSH_KEY_PATH) : undefined
};

// Database configuration
const dbConfig = {
  host: process.env.PROD_DB_HOST || 'localhost', // Usually localhost when tunneling
  user: process.env.PROD_DB_USER,
  password: process.env.PROD_DB_PASSWORD,
  database: process.env.PROD_DB_NAME,
  port: process.env.PROD_DB_PORT || 3306
};

async function testConnection() {
  const ssh = new Client();

  try {
    // Create new Promise for SSH connection
    await new Promise((resolve, reject) => {
      ssh.on('ready', resolve)
         .on('error', reject)
         .connect(sshConfig);
    });

    console.log('SSH Connection successful!');

    // Forward local port to remote MySQL port
    const tunnel = await new Promise((resolve, reject) => {
      ssh.forwardOut(
        '127.0.0.1',
        0,
        dbConfig.host,
        dbConfig.port,
        (err, stream) => {
          if (err) reject(err);
          resolve(stream);
        }
      );
    });

    console.log('Port forwarding established');

    // Create MySQL connection over SSH tunnel
    const connection = await mysql.createConnection({
      ...dbConfig,
      stream: tunnel
    });

    console.log('MySQL Connection successful!');

    // Test query
    const [rows] = await connection.query('SELECT COUNT(*) as count FROM products');
    console.log('Query successful! Product count:', rows[0].count);

    // Clean up
    await connection.end();
    ssh.end();
    console.log('Connections closed successfully');
    return rows[0].count;

  } catch (error) {
    console.error('Error:', error);
    if (ssh) ssh.end();
    throw error;
  }
}

// If running directly (not imported)
if (require.main === module) {
  testConnection()
    .then(() => process.exit(0))
    .catch(error => {
      console.error('Test failed:', error);
      process.exit(1);
    });
}

module.exports = { testConnection }; 