This is probably one of the most difficult questions to answer or understand the answer. I honestly don't have a good answer for you but I'll provide a link at the bottom of this post that may be helpful.
One thing I will say is that most of us are but infants in our walk of faith and as we continue daily searching His Word we grow and mature in our faith. We don't always know or understand why God does the things He does and in this life we may never know all the answers. The apostle Paul put it this way.
11 When I was a child, I spoke as a child, I understood as a child, I thought as a child; but when I became a man, I put away childish things.
12 For now we see in a mirror, dimly, but then face to face. Now I know in part, but then I shall know just as I also am known.
1 Corinthians 13:11-12 NKJV
God knows the beginning from the end and He knows what is best. Every day I pray that I trust all my struggles into His hands. That does not mean I don't still have questions but I do know that I can trust Him to do what He deems best and that's good enough for me.
https://www.gotquestions.org/bad-things-good-people.html