Reproducing the CO-to-H2 conversion factor in cosmological simulations of Milky-Way-mass galaxies