# frozen_string_literal: true

require "bundler/setup"
require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

require "rubocop/rake_task"

RuboCop::RakeTask.new

task default: %i[spec rubocop]

desc "Bundles the Security Report Schemas into the project"
task :prepare_schemas, [:versions] do |_, args|
  require "gitlab/security_report_schemas"
  require "gitlab/security_report_schemas/cli/schema_downloader"

  requested_versions = args.fetch(:versions, "").split.map do |ver|
    Gitlab::SecurityReportSchemas::SchemaVer.new!(ver, fallback: false)
  end

  cleanup_schema_dir.then { schemas_to_prepare(requested_versions) }
                    .then { copy_new_schemas(_1) }
                    .then { update_gem_version }
end

desc "Bundles the Security Report Schemas into the project and builds the gem"
task :prepare, %i[versions] => %i[prepare_schemas build]

desc "Checks the integrity of the schema files with upstream"
task integrity_check: :prepare_schemas do
  require "gitlab/security_report_schemas"
  require "gitlab/security_report_schemas/cli/integrity_checker"

  Gitlab::SecurityReportSchemas.supported_versions.each do |version|
    puts "Checking the integrity of #{version} schemas"

    Gitlab::SecurityReportSchemas::CLI::IntegrityChecker.check!(version)
  end
end

def cleanup_schema_dir
  puts "Cleaning the schemas directory..."

  Gitlab::SecurityReportSchemas.schema_directories.each(&:rmtree)
end

def versions_file
  @versions_file ||= Gitlab::SecurityReportSchemas.root_path
                                                  .join("supported_versions")
                                                  .then { |path| File.open(path, "r+") }
end

def schemas_to_prepare(requested_versions)
  supported_versions = versions_file.readlines.map(&:chomp)

  if requested_versions.empty?
    puts "Preparing schemas from `supported_versions' file..."
  else
    puts %(Preparing new schemas #{requested_versions.map(&:version).join(",")})
  end

  supported_versions + requested_versions
end

def copy_new_schemas(versions)
  versions_file.seek(0)

  versions.uniq.each do |version|
    puts "Preparing the schemas for #{version}"

    versions_file.puts(version)
    Gitlab::SecurityReportSchemas::CLI::SchemaDownloader.download(version)
  end

  versions_file.close
end

def update_gem_version
  # Writing the gemversion file so the gemspec can be updated
  new_gem_version = Gitlab::SecurityReportSchemas::Version.to_s
  gem_version_file = Gitlab::SecurityReportSchemas.root_path.join("gem_version")

  gem_version_file.write(new_gem_version)

  puts "Gem version is updated as `#{new_gem_version}'"
end
