# frozen_string_literal: true

module GitlabQuality
  module TestTooling
    module TestResult
      class JUnitTestResult < BaseTestResult
        attr_accessor :testcase # Ignore it for now

        def name
          report['name']
        end

        def file
          report['file']&.delete_prefix('./')
        end

        def skipped?
          report.search('skipped').any?
        end

        def failures # rubocop:disable Metrics/AbcSize
          failures = report.search('failure')
          return [] if failures.empty?

          failures.map do |exception|
            trace = exception.content.split("\n").map(&:strip)
            spec_file_first_index = trace.rindex do |line|
              report['file'] && line.include?(File.basename(report['file']))
            end

            exception['message'].gsub!(/(private_token=)[\w-]+/, '********')
            exception['message'].gsub!(/("Authorization": \[\n\s*"token )([\w-]+)/, '\1********')
            exception.content = exception.content.gsub(/(private_token=)[\w-]+/, '********')
            exception.content = exception.content.gsub(/("Authorization": \[\n\s*"token )([\w-]+)/, '\1********')
            {
              'message' => "#{exception['type']}: #{exception['message']}",
              'stacktrace' => trace.slice(0..spec_file_first_index).join("\n"),
              'message_lines' => trace.slice(0..spec_file_first_index)
            }
          end
        end

        def quarantine
          !report['quarantine'].nil?
        end

        def quarantine?
          # The value for 'quarantine' could be nil, a hash, a string,
          # or true (if the test just has the :quarantine tag)
          # But any non-nil or false value should means the test is in quarantine
          !!quarantine
        end

        def line_number
          report['line_number']
        end

        def level
          report['level']
        end

        def run_time
          report['run_time'].to_f.round(2)
        end

        def screenshot
          report['screenshot']
        end

        def screenshot?
          !!screenshot
        end

        def max_duration_for_test
          ""
        end

        def ci_job_url
          ENV.fetch('CI_JOB_URL', '')
        end

        def product_group
          report['product_group'].to_s
        end

        def product_group?
          product_group != ''
        end

        def feature_category
          report['feature_category']
        end

        def failure_issue
          report['failure_issue']
        end

        def failure_issue=(new_failure_issue)
          report['failure_issue'] = new_failure_issue
        end

        def test_file_link
          return "" if file.nil?

          path_prefix = file.start_with?('qa/') ? 'qa/' : ''

          "[`#{path_prefix}#{file}#L#{line_number}`](#{Runtime::Env.file_base_url}#{path_prefix}#{file}#L#{line_number})"
        end
      end
    end
  end
end