Can I buy a phone and set up an account for a friend and then switch account and identity to them?
You can buy a phone for a friend.
But, I would recommend that you set it up with a new account in their name. If you need to make any initial monthly payments for them, you can still bill it to your credit card.
Transferring account ownership after the fact, although feasible…is a slow laborious process that may take some time and if you can avoid it, then that would definitely be the way to go.
As there is a “terms of service” to agree to, ideally the person who will maintain ownership of the account should be the one to agree to those terms.