def migrate_travels_sql(institution_id)
  "INSERT INTO institution_travels
  SELECT ''
     , #{institution_id}
     , t1.des_titulo
     , TRIM(CONCAT(t2.fun_nombres, ' ', t2.fun_apellidos))
     , t1.des_destino
     , t3.pla_titulo
     , t1.des_fecha
     , t1.des_fecha_fin
     , t1.des_valor_pasaje
     , t1.des_valor_alojamiento
     , t1.des_valor_viaticos
     , t1.des_descripcion
     , t1.des_otros_gastos
     , TRIM(CONCAT(TRIM(REPLACE(t1.des_ente_nombre, '.', '')), (SELECT IF(TRIM(t1.des_ente_aporte) != '', ': ', '')), TRIM(t1.des_ente_aporte)))
     , NOW()
     , NOW()
    FROM goes_goe_des_destino t1
    LEFT JOIN goes_goe_fun_funcionario t2
      ON (t1.des_id_fun = t2.fun_id)
    LEFT JOIN goes_goe_pla_plaza t3
      ON (t2.fun_id_pla = t3.pla_id)"
end

def normalize_travels(institution_id)
  InstitutionTravel.all.each do |institution_travel|
    institution_travel.objetive = ActionController::Base.helpers.sanitize(institution_travel.objetive, tags: %w(br)).strip.gsub('<br />', "\n")
  end
end

def destroy_travels_sql(institution_id)
  "DELETE FROM institution_travels WHERE institution_id = #{institution_id}"
end

namespace :institution_travels do
  desc 'Migrate institution_remunerations'
  task :migrate, [:institution_id] => :environment do |tsk, args|
    ActiveRecord::Base.connection().execute(migrate_travels_sql(args[:institution_id]))
    normalize_travels(args[:institution_id])
  end
  
  task :destroy, [:institution_id] => :environment do |tsk, args|
    ActiveRecord::Base.connection().execute(destroy_travels_sql(args[:institution_id]))
  end
end