# frozen_string_literal: true

class AutoTopUpRepo
	def initialize(redis: REDIS, db: DB)
		@redis = redis
		@db = db
	end

	def find(customer_id)
		redis(:get, customer_id)
	end

	def put(customer_id, amount)
		if amount >= 15
			redis(:set, customer_id, amount)
			reset_low_balance_lock(customer_id)
			@db.exec_params(
				"SELECT check_and_notify_low_balance($1)",
				[customer_id]
			)
		elsif amount.zero?
			redis(:del, customer_id)
		end
	end

protected

	def redis(action, customer_id, *args)
		@redis.public_send(
			action,
			"jmp_customer_auto_top_up_amount-#{customer_id}",
			*args
		)
	end

	def reset_low_balance_lock(customer_id)
		@redis.del("jmp_customer_low_balance-#{customer_id}")
	end
end
