const { Pool } = require('pg');
const config = require('../config')

let writePool, readPool;

// Always create write pool
writePool = new Pool({
  user: config.db.user,
  password: config.db.password,
  host: config.db.host,
  port: config.db.port,
  database: config.db.database,
  max: config.db.maxConnections,
});

// Create read pool only in cloud mode
if (config.site.deployment === 'cloud') {
  readPool = new Pool({
    user: config.db.user,
    password: config.db.password,
    host: config.db.readHost,
    port: config.db.port,
    database: config.db.database,
    max: config.db.maxConnections,
  });
} else {
  // In self-hosted mode, use the same pool for reads and writes
  readPool = writePool;
}



// Helper function that automatically routes queries
const query = async (text, params, options = {}) => {
  const { forceWrite = false } = options;
  
  const isWrite = forceWrite || 
    text.trim().toUpperCase().startsWith('INSERT') ||
    text.trim().toUpperCase().startsWith('UPDATE') ||
    text.trim().toUpperCase().startsWith('DELETE') ||
    text.trim().toUpperCase().includes('FOR UPDATE');
  
  const pool = isWrite ? writePool : readPool;
  const start = Date.now();
  const res = await pool.query(text, params);
  const duration = Date.now() - start;
  
  if (config.site.deployment === 'cloud') {
    console.log('Executed query', { 
      text, 
      duration, 
      rows: res.rowCount,
      pool: isWrite ? 'write' : 'read'
    });
  } else {
    console.log('Executed query', { text, duration, rows: res.rowCount });
  }
  
  return res;
};


// Old Query function
// const query = async (text, params) => {
//   const start = Date.now();
//   const res = await pool.query(text, params);
//   const duration = Date.now() - start;
//   console.log('Executed query', { text, duration, rows: res.rowCount });
//   return res;
// };


module.exports = { query, pool: writePool };