import { Pool } from "pg";
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: { rejectUnauthorized: false },
  max: 20,
  idleTimeoutMillis: 3e4,
  connectionTimeoutMillis: 1e4
});
async function queryWithRLS(query2, params = [], userId) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    if (userId) {
      await client.query(`SET LOCAL app.user_id = '${userId.replace(/'/g, "''")}'`);
    }
    const result = await client.query(query2, params);
    await client.query("COMMIT");
    return result.rows;
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}
async function queryOneWithRLS(query2, params = [], userId) {
  const rows = await queryWithRLS(query2, params, userId);
  return rows[0] || null;
}
async function mutateWithRLS(query2, params = [], userId) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    if (userId) {
      await client.query(`SET LOCAL app.user_id = '${userId.replace(/'/g, "''")}'`);
    }
    const result = await client.query(query2, params);
    await client.query("COMMIT");
    return {
      rows: result.rows,
      rowCount: result.rowCount || 0
    };
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}
async function getTransactionClient(userId) {
  const client = await pool.connect();
  await client.query("BEGIN");
  if (userId) {
    await client.query(`SET LOCAL app.user_id = '${userId.replace(/'/g, "''")}'`);
  }
  return {
    query: (query2, params = []) => client.query(query2, params).then((r) => r.rows),
    queryOne: (query2, params = []) => client.query(query2, params).then((r) => r.rows[0] || null),
    mutate: (query2, params = []) => client.query(query2, params).then((r) => ({ rows: r.rows, rowCount: r.rowCount || 0 })),
    commit: async () => {
      await client.query("COMMIT");
      client.release();
    },
    rollback: async () => {
      await client.query("ROLLBACK");
      client.release();
    }
  };
}
async function query(text, params) {
  const result = await pool.query(text, params);
  return {
    rows: result.rows,
    rowCount: result.rowCount || 0
  };
}
async function queryRows(text, params) {
  const result = await pool.query(text, params);
  return result.rows;
}
async function queryOne(text, params) {
  const result = await pool.query(text, params);
  return result.rows[0] || null;
}
async function checkDatabaseConnection() {
  try {
    const client = await pool.connect();
    await client.query("SELECT 1");
    client.release();
    return true;
  } catch (error) {
    console.error("Database connection failed:", error);
    return false;
  }
}
export {
  checkDatabaseConnection,
  getTransactionClient,
  mutateWithRLS,
  pool,
  query,
  queryOne,
  queryOneWithRLS,
  queryRows,
  queryWithRLS
};
