// src/db.js
// === SECURITY HARDENING: DATABASE ACCESS LOGGING ===
const { Pool } = require('pg');
const config = require('./config');
const { loggedQuery } = require('./middleware/dbAccessLogger');

const pool = new Pool({
  connectionString: config.databaseUrl,
});

pool.on('error', (err) => {
  console.error('Unexpected PG client error', err);
  process.exit(-1);
});

/**
 * Execute database query with optional logging and context
 * @param {string} text - SQL query
 * @param {Array} params - Query parameters
 * @param {Object} context - Request context for logging (optional)
 *   - userId: User ID from request
 *   - ipAddress: Client IP address
 *   - userAgent: User agent string
 * @returns {Promise} - Query result
 */
function query(text, params = [], context = {}) {
  // Use logged query if logging is enabled, otherwise use direct query
  const DB_ACCESS_LOGGING_ENABLED = process.env.DB_ACCESS_LOGGING_ENABLED === 'true' || process.env.DB_ACCESS_LOGGING_ENABLED === '1';
  
  if (DB_ACCESS_LOGGING_ENABLED) {
    return loggedQuery(text, params, context);
  }
  
  return pool.query(text, params);
}

/**
 * Helper to create context from Express request
 * @param {Object} req - Express request object
 * @returns {Object} - Context object for database logging
 */
function createContextFromRequest(req) {
  return {
    userId: req.user?.id || null,
    ipAddress: req.ip || req.connection?.remoteAddress || null,
    userAgent: req.headers['user-agent'] || null,
  };
}

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