import pg from 'pg';

const { Pool } = pg;

let pool: InstanceType<typeof Pool> | null = null;

function getPool(): InstanceType<typeof Pool> {
	if (!pool) {
		pool = new Pool({
			host: 'localhost',
			port: 5432,
			user: 'postgres',
			password: process.env.POSTGRES_PASSWORD || 'postgres',
			database: 'postgres'
		});
	}
	return pool;
}

/** Execute raw SQL directly against the dev database (bypasses RLS). */
export async function sql(query: string, params: unknown[] = []): Promise<pg.QueryResult> {
	return getPool().query(query, params);
}

/** Close the connection pool (call in afterAll if using db-helpers). */
export async function closePool(): Promise<void> {
	if (pool) {
		await pool.end();
		pool = null;
	}
}
