# frozen_string_literal: true

class Transaction
	def initialize(customer_id, id, amount, note, settled_after: Time.now)
		@customer_id = customer_id
		@id = id
		@amount = amount
		@note = note
		@after = settled_after
	end

	def bonus
		return unless bonus_amount.positive?

		self.class.new(
			@customer_id,
			"bonus_for_#{@id}",
			bonus_amount,
			"#{@note} bonus"
		)
	end

	def bonus_amount
		return BigDecimal(0) if @amount <= 15

		@amount * case @amount
		when (15..29.99)
			0.01
		when (30..139.99)
			0.03
		else
			0.05
		end
	end

	def save
		args = [@customer_id, @id, @amount, @note, @after]
		DB.exec_params(<<-SQL, args).cmd_tuples.positive?
			INSERT INTO transactions
				(customer_id, transaction_id, settled_after, amount, note)
			VALUES
				($1, $2, $5, $3, $4)
			ON CONFLICT (transaction_id) DO NOTHING
		SQL
	end
end
