# frozen_string_literal: true
module Issues
  class CreateFromVulnerabilityService < ::BaseContainerService
    def execute
      return error("User is not permitted to create issue") unless can?(@current_user, :create_issue, @container)

      vulnerability = params[:vulnerability].present
      link_type = params[:link_type]

      return error("Vulnerability not found") unless vulnerability
      return error("Invalid link type for Vulnerability") unless link_type

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

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

        if issue.valid?
          issue_link_creation_result = VulnerabilityIssueLinks::CreateService.new(
            @current_user,
            vulnerability.subject,
            issue,
            link_type: link_type
          ).execute

          error(issue_link_creation_result.errors) if issue_link_creation_result.error?

          success(issue)
        else
          error(issue.errors)
        end
      end
    end

    private

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

    def render_description(vulnerability)
      ApplicationController.render(
        template: 'vulnerabilities/issue_description.md.erb',
        locals: { vulnerability: vulnerability }
      )
    end
  end
end
