import pg from 'pg';

const { Pool } = pg;

let pool: pg.Pool | null = null;

export function getPool(): pg.Pool {
  if (!pool) {
    const connectionString = process.env.DATABASE_URL;
    if (!connectionString) {
      throw new Error('DATABASE_URL environment variable is not set');
    }
    pool = new Pool({ connectionString, max: 10 });
  }
  return pool;
}

export async function query(text: string, params?: any[]): Promise<pg.QueryResult<any>> {
  const p = getPool();
  return p.query(text, params);
}

export async function getClient(): Promise<pg.PoolClient> {
  return getPool().connect();
}

export function log(message: string, ...args: any[]): void {
  const ts = new Date().toISOString();
  console.log(`[${ts}] ${message}`, ...args);
}

export function logError(message: string, error?: any): void {
  const ts = new Date().toISOString();
  console.error(`[${ts}] ERROR: ${message}`, error?.message || error || '');
}
