# frozen_string_literal: true

# The ProjectVulnerabilityFindingsActions concern contains actions that are used to populate findings
# on security dashboards.
#
# Note: Consumers of this module will need to define a `def vulnerable` method, which must return
# an object with an interface that matches the one provided by the Vulnerable model concern.

module ProjectVulnerabilityFindingsActions
  extend ActiveSupport::Concern

  def index
    findings = vulnerability_findings(:with_sha).ordered.page(params[:page])

    respond_to do |format|
      format.json do
        render json: Vulnerabilities::OccurrenceSerializer
          .new(current_user: current_user)
          .with_pagination(request, response)
          .represent(findings, preload: true)
      end
    end
  end

  def summary
    summary = Gitlab::Vulnerabilities::Summary.new(vulnerable, filter_params).findings_counter

    respond_to do |format|
      format.json do
        render json: summary
      end
    end
  end

  private

  def filter_params
    params.permit(:scope, report_type: [], confidence: [], project_id: [], severity: [])
  end

  def vulnerability_findings(collection = :latest)
    ::Security::VulnerabilityFindingsFinder.new(vulnerable, params: filter_params).execute(collection)
  end
end
