# frozen_string_literal: true

class VulnerabilityPresenter < Gitlab::View::Presenter::Delegated
  presents :vulnerability

  def links
    vulnerability.links.map(&:with_indifferent_access)
  end

  def remediations
    vulnerability.remediations.to_a.compact.map(&:with_indifferent_access)
  end

  def location_text
    return file unless line

    "#{file}:#{line}"
  end

  def location_link
    return location_text unless blob_path

    "#{root_url}#{blob_path}"
  end

  def blob_path
    return unless file

    branch = finding.pipelines&.last&.sha || project.default_branch
    path = project_blob_path(vulnerability.project, File.join(branch, file))

    return unless path

    path = path.gsub(/^\//, '')

    add_line_numbers(path, finding.location['start_line'], finding.location['end_line'])
  end

  def scanner
    finding.scanner || {}
  end

  def scan
    finding.scan || {}
  end

  private

  def root_url
    Gitlab::Routing.url_helpers.root_url
  end

  def line
    finding.location.dig("start_line")
  end

  def file
    finding.location.dig("file")
  end

  def add_line_numbers(path, start_line, end_line)
    return path unless start_line

    path.tap do |complete_path|
      complete_path << "#L#{start_line}"
      complete_path << "-#{end_line}" if end_line != start_line
    end
  end
end
