# frozen_string_literal: true

module VulnerabilityIssueLinks
  class CreateService < BaseService
    def initialize(user, vulnerability, issue, link_type: Vulnerabilities::IssueLink.link_types[:related])
      @user = user
      @vulnerability = vulnerability
      @issue = issue
      @link_type = link_type
    end

    def execute
      raise Gitlab::Access::AccessDeniedError unless can?(@user, :admin_vulnerability_issue_link, issue_link)

      if issue_link.save
        success
      else
        error
      end
    end

    private

    def issue_link
      @issue_link ||= Vulnerabilities::IssueLink.new(vulnerability: @vulnerability, issue: @issue, link_type: @link_type)
    end

    def success
      ServiceResponse.success(payload: result_payload, http_status: 200)
    end

    def error
      ServiceResponse.error(
        message: issue_link.errors.full_messages.to_sentence,
        payload: result_payload,
        http_status: 422)
    end

    def result_payload
      { record: issue_link }
    end
  end
end
