Sequel.migration do
  up do
    processes_with_meta_commands = self[:processes].where(Sequel.like(:metadata, '%command%'))

    processes_with_meta_commands.each do |process_record|
      # for_update will acquire a row level lock in the database
      # We need to force the dataset to evaluate by calling #first to get it to take effect
      self[:processes].where(guid: process_record[:guid]).for_update.first

      begin
        process_metadata = Oj.load(process_record[:metadata])
      rescue StandardError
        # ignore
      end
      process_metadata_command = process_metadata && process_metadata['command']

      fields_to_update = { metadata: process_metadata.except('command').to_json }
      fields_to_update[:command] = process_metadata_command if process_metadata_command && process_record[:command].blank?

      self[:processes].where(guid: process_record[:guid]).update(fields_to_update)
    end

    processes_with_commands = self[:processes].exclude(command: nil)

    processes_with_commands.each do |process_record|
      app_record = self[:apps].where(guid: process_record[:app_guid]).for_update.first
      droplet_record = self[:droplets].where(guid: app_record[:droplet_guid]).for_update.first

      # for_update will acquire a row level lock in the database
      # We need to force the dataset to evaluate by calling #first to get it to take effect
      self[:processes].where(guid: process_record[:guid]).for_update.first

      next unless droplet_record

      begin
        droplet_commands_by_type = Oj.load(droplet_record[:process_types])
      rescue StandardError
        # ignore
      end
      droplet_command = droplet_commands_by_type && droplet_commands_by_type[process_record[:type]]

      self[:processes].where(guid: process_record[:guid]).update(command: nil) if droplet_command == process_record[:command]
    end
  end

  down do
  end
end
