import pg from 'pg';
import { DEFAULT_DATABASE_URL } from '../../config/src/index.js';

const { Pool } = pg;

export interface DbPoolOptions {
  connectionString?: string;
  max?: number;
  idleTimeoutMillis?: number;
}

export function createPool(options: DbPoolOptions = {}) {
  return new Pool({
    connectionString: options.connectionString || process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
    max: options.max || 10,
    idleTimeoutMillis: options.idleTimeoutMillis || 30_000,
  });
}

export async function query<T = unknown>(pool: pg.Pool, sql: string, params: unknown[] = []): Promise<T[]> {
  const result = await pool.query(sql, params);
  return result.rows as T[];
}

export async function queryOne<T = unknown>(pool: pg.Pool, sql: string, params: unknown[] = []): Promise<T | null> {
  const rows = await query<T>(pool, sql, params);
  return rows[0] ?? null;
}
