# 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 that includes an `#all_pipelines` method

module ProjectVulnerabilityFindingsActions
  extend ActiveSupport::Concern

  def index
    pipeline_ids = vulnerable.all_pipelines.with_vulnerabilities.latest_successful_ids_per_project
    findings = ::Security::VulnerabilityFindingsFinder.new(pipeline_ids, params: filter_params, include_sha: true).execute
    ordered_findings = findings.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(ordered_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
end
