# frozen_string_literal: true

module VulnerabilityFeedback
  class DestroyService < ::BaseService
    include Gitlab::Utils::StrongMemoize

    def initialize(project, user, vulnerability_feedback, revert_vulnerability_state: true)
      @project = project
      @current_user = user
      @vulnerability_feedback = vulnerability_feedback
      @revert_vulnerability_state = revert_vulnerability_state
    end

    def execute
      # TODO: Add system note when destroying a dismissal feedback
      raise Gitlab::Access::AccessDeniedError unless can?(current_user, :destroy_vulnerability_feedback, vulnerability_feedback)

      revert_vulnerability if revert_vulnerability_state?
      vulnerability_feedback.destroy
    end

    private

    attr_reader :vulnerability_feedback, :revert_vulnerability_state

    def revert_vulnerability
      Vulnerabilities::RevertToDetectedService.new(current_user, existing_vulnerability).execute
    end

    def revert_vulnerability_state?
      revert_vulnerability_state && existing_vulnerability
    end

    def existing_vulnerability
      strong_memoize(:existing_vulnerability) { vulnerability_feedback.finding&.vulnerability }
    end
  end
end
