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

class Database {
  constructor() {
    this.pool = new Pool({
      host: process.env.POSTGRES_HOST || 'localhost',
      port: process.env.POSTGRES_PORT || 5432,
      database: process.env.POSTGRES_DB || 'dev_pipeline',
      user: process.env.POSTGRES_USER || 'pipeline_admin',
      password: process.env.POSTGRES_PASSWORD || 'secure_pipeline_2024',
      max: 20,
      idleTimeoutMillis: 30000,
      connectionTimeoutMillis: 2000,
    });

    // Test connection on startup
    this.testConnection();
  }

  async testConnection() {
    try {
      const client = await this.pool.connect();
      console.log('✅ Database connected successfully');
      client.release();
    } catch (err) {
      console.error('❌ Database connection failed:', err.message);
      process.exit(1);
    }
  }

  async query(text, params) {
    const start = Date.now();
    try {
      const res = await this.pool.query(text, params);
      const duration = Date.now() - start;
      console.log('📊 Query executed:', { text: text.substring(0, 50), duration, rows: res.rowCount });
      return res;
    } catch (err) {
      console.error('❌ Query error:', err.message);
      throw err;
    }
  }

  async getClient() {
    return await this.pool.connect();
  }

  async connect() {
    return await this.pool.connect();
  }

  async close() {
    await this.pool.end();
    console.log('🔌 Database connection closed');
  }
}

module.exports = new Database();