class MaterialSyncSuppressionRegistrar
  def self.create! attributes, created_by_user:
    new(attributes, created_by_user:).create!
  end

  def initialize attributes, created_by_user:
    @attributes = attributes
    @created_by_user = created_by_user
  end

  def create!
    suppression = nil

    MaterialSyncSuppression.transaction do
      suppression = MaterialSyncSuppression.create!(
          @attributes.merge(created_by_user: @created_by_user))
      discard_existing_materials!(suppression)
    end

    suppression
  end

  private

  def discard_existing_materials! suppression
    matching_materials(suppression).find_each do |material|
      MaterialVersionRecorder.ensure_snapshot!(material, created_by_user: @created_by_user)
      material.discard!
      MaterialVersionRecorder.record!(material:,
                                      event_type: :discard,
                                      created_by_user: @created_by_user)
    end
  end

  def matching_materials suppression
    materials = Material.unscoped.kept

    case suppression.source_kind
    when 'google_drive_path', 'legacy_drive_path'
      materials.where(source_path: suppression.drive_path)
    when 'google_drive_path_prefix', 'legacy_drive_path_prefix'
      path = suppression.drive_path.to_s
      materials.where(
          'source_path = :path OR source_path LIKE :prefix',
          path:,
          prefix: "#{ path }/%")
    else
      materials.where(normalized_source_key: suppression.normalized_source_key)
    end
  end
end
