using Distribution.Infra.UoW; namespace Distribution.Features.Role; public class RoleService(IRoleRepository repo, IUnitOfWork uow) { private static RoleResponse ToResponse(Models.Role r) => new(r.Id, r.Name, r.Level, r.IsActive, r.CreatedAt); public async Task> GetAllAsync() => (await repo.GetAllAsync()) .Where(r => r.IsActive) .Select(ToResponse) .ToList(); public async Task GetByIdAsync(Guid id) { var role = await repo.GetByIdAsync(id); if (role is null || !role.IsActive) return null; return ToResponse(role); } public async Task?> GetPermissionsAsync(Guid roleId) { var role = await repo.GetByIdAsync(roleId); if (role is null || !role.IsActive) return null; return (await repo.GetPermissionsAsync(roleId)) .Select(rp => new RolePermissionResponse(rp.FK_PermissionId, rp.Permission.Code, rp.Permission.Description)) .ToList(); } public async Task CreateAsync(CreateRoleRequest request, CancellationToken ct = default) { var role = new Models.Role { Name = request.Name, Level = request.Level }; await uow.BeginAsync(ct); try { await repo.AddAsync(role); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return ToResponse(role); } public async Task UpdateAsync(Guid id, UpdateRoleRequest request, CancellationToken ct = default) { var role = await repo.GetByIdAsync(id); if (role is null || !role.IsActive) return null; role.Name = request.Name; role.Level = request.Level; await uow.BeginAsync(ct); try { repo.Update(role); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return ToResponse(role); } public async Task DeactivateAsync(Guid id, CancellationToken ct = default) { var role = await repo.GetByIdAsync(id); if (role is null || !role.IsActive) return false; await uow.BeginAsync(ct); try { repo.Remove(role); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return true; } public async Task?> AssignPermissionsAsync(Guid id, AssignRolePermissionsRequest request, CancellationToken ct = default) { var role = await repo.GetByIdAsync(id); if (role is null || !role.IsActive) return null; await uow.BeginAsync(ct); try { await repo.ReplacePermissionsAsync(id, request.PermissionIds); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return await GetPermissionsAsync(id); } }