We aren't adapted to maximise our chances of survival in a medically advanced setting, but one where there is no or minimal assistance.
Hence, many of the things which the body does when badly injured or in its dying phases is unhelpful medically, now - but reflects mechanisms that might have helped, some of the time, in a situation where you either get away (and survive) or simply die on your own.
The kind of major injuries and illnesses we survive now, would never have been survivable in millenia past - hence it is understandable that the body has poor adaptation to them (it could not possibly convey an advantage if death is inevitable).
The endorphins released in death/dying, may be a reflection of adrenaline etc rushing around the body in this state (the body's only way to try to survive without help). Endorphins are useful in the presence of adrenaline, as they give the psychological energy to accompany physical energy ("runner's high" "fight or flight"). Their presence may convey an advantage in dangerous injury/situations that the individual may have a chance of surviving on their own.
OR, their release may just be a form of brain dysfunction in death. Cells release their contents in death.
These are just things that would make sense - I haven't looked at any sources, so it's not a specific answer I'm afraid. Just a general one to "why does the body do stuff which is medically unhelpful?". The answer: it's not adapted to be medically helpful, because for millenia there has been no medicine.