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

// PostgreSQL connection to eluxnetworks.net
const pool = new Pool({
  host: process.env.DB_HOST || 'eluxnetworks.net',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'wellnuo_app',
  user: process.env.DB_USER || 'sergei',
  password: process.env.DB_PASSWORD,

  // SSL required for remote connections
  ssl: {
    rejectUnauthorized: false
  },

  // Connection pool settings
  max: 20,                    // Maximum connections
  idleTimeoutMillis: 30000,   // Close idle connections after 30s
  connectionTimeoutMillis: 10000  // Timeout after 10s
});

// Test connection on startup
pool.on('connect', () => {
  console.log('Connected to PostgreSQL database');
});

pool.on('error', (err) => {
  console.error('PostgreSQL pool error:', err);
});

// Helper for simple queries
const query = async (text, params) => {
  const start = Date.now();
  const result = await pool.query(text, params);
  const duration = Date.now() - start;

  if (process.env.NODE_ENV !== 'production') {
    console.log('Query:', { text: text.substring(0, 100), duration, rows: result.rowCount });
  }

  return result;
};

// Helper for transactions
const getClient = async () => {
  const client = await pool.connect();
  return client;
};

module.exports = {
  pool,
  query,
  getClient
};
