require 'rake/testtask'

# Tests namespace :test do

desc 'Test ForemanThemeSatellite'
Rake::TestTask.new(:foreman_theme_satellite) do |t|
  test_dir = File.expand_path('../../test', __dir__)
  t.libs << 'test'
  t.libs << test_dir
  t.pattern = "#{test_dir}/**/*_test.rb"
  t.verbose = true
  t.warning = false
end

end

namespace :foreman_theme_satellite do

desc 'Validate documentation links against given TOC file'
task :validate_docs do
  toc_file = ENV['TOC']
  unless toc_file
    toc_file = File.expand_path('../../test/fixtures/toc.json', __dir__)
    puts "Using default TOC: #{toc_file}, to override please specify TOC=<toc_file>"
  end
  aliases_file = ENV['ALIASES']
  unless aliases_file
    aliases_file = File.expand_path('../../test/fixtures/aliases.json', __dir__)
    puts "Using default ALIASES: #{aliases_file}, to override please specify ALIASES=<aliases_file>"
  end

  require_relative '../../test/link_checker'
  checker = LinksChecker.new(toc: toc_file, aliases: aliases_file)

  require_relative '../foreman_theme_satellite/documentation'

  all_links = ForemanThemeSatellite::Documentation::USER_GUIDE_DICTIONARY
              .merge(ForemanThemeSatellite::Documentation::PLUGINS_DOCUMENTATION)
              .merge(ForemanThemeSatellite::Documentation.flat_docs_guides_links)

  # The links are either
  # - path fragments - managing_hosts/index#data-control-settings
  # - full URLs - https://access.redhat.com/products/red-hat-satellite/#support
  failed = all_links.filter { |_key, doc_address| !doc_address.start_with?('http') && !checker.test_link(doc_address) }

  abort((failed.map { |key, doc_address| "FAILED: Cannot find #{doc_address} in TOC for entry: #{key}" } + ["Total failed: #{failed.count} entries"]).join("\n")) unless failed.empty?

  puts "Successfully tested #{all_links.count} links"
end

end

Rake::Task.enhance ['test:foreman_theme_satellite'] Rake::Task.enhance ['foreman_theme_satellite:validate_docs']