require 'gds_api/router'

router = GdsApi::Router.new(Plek.current.find('router-api'))

Document.find_by_sql("SELECT *, LENGTH(slug) AS slug_length FROM documents HAVING `slug_length` > 250;").each do |document|
  if published = document.published_edition
    old_slug = document.slug
    old_path = Whitehall.url_maker.document_path(published)
    new_slug = document.normalize_friendly_id(published.title)
    puts "Changing '#{old_slug}' to '#{new_slug}' for document '#{document.id}'"
    document.update_attribute(:slug, new_slug)
    new_path = Whitehall.url_maker.document_path(published.reload)
    puts "Redirecting '#{old_path}' to '#{new_path}'"
    router.add_redirect_route(old_path, 'exact', new_path)
  end
end

Add a data migration to trim excessive slugs
Add a data migration to trim excessive slugs

We introduced a limit on slug length in ca28979, however documents
created before this time don't conform to this validation, which breaks
the crawler.

This data migration cleans up the old slugs for published editions by
updating their slugs to the new maximum length and redirecting the old
URLs to the new URLs.
