import pg from 'pg';

const { Pool } = pg;

export function createPool(envPrefix = 'DB', overrides = {}) {
  const get = (key) => process.env[`${envPrefix}_${key}`];

  return new Pool({
    host: overrides.host ?? get('HOST'),
    user: overrides.user ?? get('USER'),
    password: overrides.password ?? get('PASSWORD'),
    database: overrides.database ?? get('NAME'),
    port: overrides.port ?? (Number(get('PORT')) || 5432),
    ssl: (overrides.ssl ?? get('SSL')) === 'true' ? { rejectUnauthorized: false } : false,
    max: overrides.max ?? 20,
    idleTimeoutMillis: overrides.idleTimeoutMillis ?? 30_000,
    connectionTimeoutMillis: overrides.connectionTimeoutMillis ?? 5_000,
    // Pin the session timezone to business time (see docs/TIME.md) so date
    // bucketing can't silently revert if the database default changes.
    options: overrides.options ?? '-c TimeZone=America/Chicago',
  });
}
