'use strict'

const { Pool } = require('pg')

const pool = new Pool({
  host:     process.env.PG_HOST     || 'localhost',
  port:     parseInt(process.env.PG_PORT || '5432'),
  database: process.env.PG_DATABASE || 'alemao',
  user:     process.env.PG_USER     || 'newwhats',
  password: process.env.PG_PASSWORD || 'newwhats123',
  max:      10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
})

pool.on('error', (err) => {
  console.error('❌ Erro inesperado no pool PostgreSQL:', err)
})

/**
 * Executa uma query SELECT e retorna todas as linhas.
 */
async function query(sql, params = []) {
  const client = await pool.connect()
  try {
    const result = await client.query(sql, params)
    return result.rows
  } finally {
    client.release()
  }
}

/**
 * Executa uma query SELECT e retorna apenas a primeira linha.
 */
async function queryOne(sql, params = []) {
  const rows = await query(sql, params)
  return rows[0] || null
}

/**
 * Executa INSERT/UPDATE/DELETE e retorna o resultado.
 */
async function execute(sql, params = []) {
  const client = await pool.connect()
  try {
    const result = await client.query(sql, params)
    return {
      rowCount: result.rowCount,
      rows: result.rows,
      lastInsertRowid: result.rows[0]?.id || null,
    }
  } finally {
    client.release()
  }
}

/**
 * Executa múltiplas queries em uma única transação atômica.
 * Uso: await transaction(async (client) => { await client.query(...) })
 */
async function transaction(fn) {
  const client = await pool.connect()
  try {
    await client.query('BEGIN')
    const result = await fn(client)
    await client.query('COMMIT')
    return result
  } catch (err) {
    await client.query('ROLLBACK')
    throw err
  } finally {
    client.release()
  }
}

module.exports = { pool, query, queryOne, execute, transaction }
