import { Pool } from 'pg';
import { config } from '../config';

const pool = new Pool({ connectionString: config.database.url });

export interface DbQueryInput {
  query: string;
  params?: any[];
  datasource?: string;
  timeout?: number;
}

export interface DbQueryOutput {
  rows: any[];
  rowCount: number;
}

/**
 * Execute a database SELECT query.
 */
export async function dbQuery(input: DbQueryInput): Promise<DbQueryOutput> {
  const client = await pool.connect();
  try {
    if (input.timeout) {
      await client.query(`SET statement_timeout = ${input.timeout}`);
    }
    const result = await client.query(input.query, input.params || []);
    return {
      rows: result.rows,
      rowCount: result.rowCount || 0,
    };
  } finally {
    client.release();
  }
}
