import type pg from 'pg';
import { createPool, query as runQuery, queryOne as runQueryOne } from '../../../../packages/db/src/index.js';
import { DEFAULT_DATABASE_URL } from '../../../../packages/config/src/index.js';

export const pool = createPool({
  connectionString: process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
  max: 10,
});

export async function query<T = unknown>(sql: string, params: unknown[] = []): Promise<T[]> {
  return runQuery<T>(pool, sql, params);
}

export async function queryOne<T = unknown>(sql: string, params: unknown[] = []): Promise<T | null> {
  return runQueryOne<T>(pool, sql, params);
}

export async function closePool() {
  await pool.end();
}

export async function transaction<T>(callback: (client: pg.PoolClient) => Promise<T>) {
  const client = await pool.connect();
  try {
    await client.query('begin');
    const result = await callback(client);
    await client.query('commit');
    return result;
  } catch (error) {
    await client.query('rollback');
    throw error;
  } finally {
    client.release();
  }
}
