const UnitOfWork = require('../../database/UnitOfWork');
const PoolMemberRepository = require('../../repositories/pool/poolMemberRepository');

async function listMembers(poolId) {
  const uow = new UnitOfWork();
  try {
    await uow.start();
    const repo = new PoolMemberRepository(uow);
    const members = await repo.listMembers(poolId);
    await uow.commit();
    return members;
  } catch (err) {
    try { await uow.rollback(err); } catch (_) {}
    throw err;
  }
}

async function addMembers(poolId, userIds, actorUserId) {
  const uow = new UnitOfWork();
  try {
    await uow.start();
    const repo = new PoolMemberRepository(uow);
    await repo.addMembers(poolId, userIds, actorUserId);
    await uow.commit();
    return true;
  } catch (err) {
    try { await uow.rollback(err); } catch (_) {}
    throw err;
  }
}

async function removeMembers(poolId, userIds, actorUserId) {
  const uow = new UnitOfWork();
  try {
    await uow.start();
    const repo = new PoolMemberRepository(uow);
    const removed = await repo.removeMembers(poolId, userIds, actorUserId);
    await uow.commit();
    return removed;
  } catch (err) {
    try { await uow.rollback(err); } catch (_) {}
    throw err;
  }
}

module.exports = { listMembers, addMembers, removeMembers };
