module MyDiscard
  extend ActiveSupport::Concern

  included do
    include Discard::Model

    default_scope -> { kept }
  end

  class_methods do
    def find_undiscard_or_create_by! attrs, &block
      record = with_discarded.find_by(attrs)

      if record&.discarded?
        record.undiscard!
        record.update_columns(created_at: record.reload.updated_at)
      end

      record or create!(attrs, &block)
    rescue ActiveRecord::RecordNotUnique
      retry
    end
  end
end
