import pg from "pg";
import { env } from "./env.js";
const { Pool } = pg;

export const pool = new Pool({
  connectionString: env.databaseUrl,
  max: 20,
  idleTimeoutMillis: 30000,
  ssl: env.nodeEnv === "production" ? { rejectUnauthorized: false } : false,
});

export async function query(text, params = []) {
  return pool.query(text, params);
}

export async function withDbSession(user, callback) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query("SELECT set_config('app.user_id', $1, true)", [String(user?.sub || 0)]);
    await client.query("SELECT set_config('app.user_role', $1, true)", [String(user?.role || 'anonymous')]);
    await client.query("SELECT set_config('app.committee_id', $1, true)", [String(user?.committee_id || 0)]);
    const result = await callback(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}
