// Coneción Singleton a base de datos.

import { Pool } from 'pg';

class Database {
    constructor() {

        if (Database.instance) {
            return Database.instance;
        }

        const config = {
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASS,
            database: process.env.DB_NAME,
            port: process.env.DB_LOCAL_PORT ? Number(process.env.DB_LOCAL_PORT) : undefined,
            ssl: process.env.PGSSL === 'true' ? { rejectUnauthorized: false } : undefined,
        };

        this.connection = new Pool(config);
        
        Database.instance = this;
    }
    async query(sql, params) {
        return this.connection.query(sql,params);
    }

    async connect() { /* Definida solo para evitar errores */
        return this.connection.connect();
    }
    async getClient() {
        return this.connection.connect();
    }

    async release() {
        await this.connection.end();
    }
}

// const db = new Database();
// db.query('SELECT * FROM users');

const pool = new Database();
export default pool;
export { Database };