# frozen_string_literal: true

module Issues
  class CreateFromVulnerabilityDataService < ::BaseService
    def execute
      return error("User is not permitted to create issue") unless can?(@current_user, :create_issue, @project)

      begin
        vulnerability = Gitlab::Vulnerabilities::Parser.fabricate(@params)
      rescue Gitlab::Vulnerabilities::InvalidCategoryError
        return error('Invalid vulnerability category')
      end

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

      issue = Issues::CreateService.new(project: @project, current_user: @current_user, params: 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)
      ApplicationController.render(
        template: 'vulnerabilities/issue_description.md.erb',
        locals: { vulnerability: vulnerability }
      )
    end
  end
end
