namespace :partners do
  namespace :heroku do
    desc 'checks that our plans have correct partner id'
    task verify_plans: [:environment] do
      heroku = Partner.find_by!(system_name: 'heroku')

      desired = Logic::ProviderUpgrade::HEROKU_PLANS.keys.map(&:to_s)
      existing = heroku.application_plans.pluck(:system_name)

      raise "existing plans '#{existing}' are not the same as desired '#{desired}'" if existing.sort! != desired.sort!
    end

    desc 'updates existing plans with heroku partner in order to be correct'
    task fix_plans: [:environment] do
      heroku = Partner.find_by!(system_name: 'heroku')

      desired = Logic::ProviderUpgrade::HEROKU_PLANS.keys.map(&:to_s)
      existing = heroku.application_plans.pluck(:system_name)

      if existing != desired
        puts "updating plans with partner heroku in order to have correct names: '#{desired}'"
        application_plans = Account.master.application_plans.where(system_name: desired, partner_id: nil)
        application_plans.update_all(partner_id: heroku)
      end
    end
  end
end
