import { Pool } from 'pg';

let pool: Pool | null = null;

function useSsl(connectionString: string) {
  return !connectionString.includes('localhost') && !connectionString.includes('@db:');
}

export function getPool() {
  const connectionString = process.env.DATABASE_URL;

  if (!connectionString) {
    return null;
  }

  if (!pool) {
    pool = new Pool({
      connectionString,
      ssl: useSsl(connectionString) ? { rejectUnauthorized: false } : undefined
    });
  }

  return pool;
}
