import { Pool } from 'pg';
import dotenv from 'dotenv';
import path from 'path';
import { buildDatabasePoolConfig } from './config';

dotenv.config({ path: path.join(__dirname, '../../.env') });

const pool = new Pool(buildDatabasePoolConfig());

pool.on('error', (err) => {
  console.error('Unexpected DB pool error:', err);
});

export async function checkDatabaseHealth(): Promise<{ ok: true; latencyMs: number }> {
  const startedAt = Date.now();
  await pool.query('SELECT 1');
  return {
    ok: true,
    latencyMs: Date.now() - startedAt,
  };
}

export default pool;
