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: 10000,
    });

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

  async testConnection() {
    try {
      const client = await this.pool.connect();
      console.log('✅ User Auth Database connected successfully');
      client.release();
    } catch (err) {
      console.error('❌ User Auth Database connection failed:', err.message);
      // Don't exit the process, just log the error
      // The service can still start and retry connections later
    }
  }

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

  async transaction(callback) {
    const client = await this.pool.connect();
    try {
      await client.query('BEGIN');
      const result = await callback(client);
      await client.query('COMMIT');
      return result;
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

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

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

module.exports = new Database();