# frozen_string_literal: true

module Issues
  class CreateFromVulnerabilityDataService < ::BaseService
    def execute
      return error("Can't create issue") unless can?(@current_user, :create_issue, @project)

      vulnerability = case @params[:category]
                      when 'sast', 'dependency_scanning', 'dast'
                        Gitlab::Vulnerabilities::StandardVulnerability.new(params)
                      when 'container_scanning'
                        Gitlab::Vulnerabilities::ContainerScanningVulnerability.new(params)
                      end

      return error('Invalid vulnerability category') unless vulnerability

      issue_params = {
        title: "Investigate vulnerability: #{vulnerability.title}",
        description: render_description(vulnerability),
        confidential: true
      }

      issue = Issues::CreateService.new(@project, @current_user, issue_params).execute

      if issue.valid?
        success(issue)
      else
        error(issue.errors)
      end
    end

    private

    def success(issue)
      super().merge(issue: issue)
    end

    def render_description(vulnerability)
      view = ActionView::Base.new(ActionController::Base.view_paths, {})
      view.render(file: 'vulnerabilities/issue_description.md.erb', locals: { vulnerability: vulnerability })
    end
  end
end
