Lewis Hamilton will leave Mercedes at the end of the 2024 season and join Ferrari on a multi-year deal in 2025.