Use "long-term" when acting as an adjective before a noun, and "long term" otherwise.
When used as an adjective before a noun, it's generally hyphenated: "long-term." Why? The hyphen clarifies that the two words function together as a single, unified adjective.
James and Alice have a long-term contract.
James and Alice have a long term contract.
When used as a noun phrase, it should be two separate words.
My wife and I are thinking in the long term.
My wife and I are thinking in the long term.
When acting as an introductory phrase, the hyphen is usually omitted as well.
In the long term, exercise and a balanced diet will improve our overall health.
Use "long-term" when used as an adjective before a noun, and "long term" otherwise.
Keep in mind that while omitting the hyphen isn't strictly wrong, it's generally advisable to use a hyphen in "long-term" when it serves as an adjective modifying a noun. This is also a widely followed practice.
The long-term effects of smoking are detrimental to your health.
We are developing a long-term strategy for sustainable growth.
Apply the same approach to the terms "short-term" and "medium-term."