On first glance this feels like a pretty confusing controller action with a lot of conditionals. Let's pair on how to re-factor.