class BtcpayCheckDonationJob < ApplicationJob
  queue_as :default

  def perform(donation)
    return if donation.completed?

    invoice = BtcpayManager::FetchInvoice.call(
      invoice_id: donation.btcpay_invoice_id
    )

    case invoice["status"]
    when "Settled"
      donation.paid_at = DateTime.now
      donation.payment_status = "settled"
      donation.save!

      NotificationMailer.with(user: donation.user)
                        .bitcoin_donation_confirmed
                        .deliver_later
    when "Processing"
      re_enqueue_job(donation)
    end
  end

  def re_enqueue_job(donation)
    self.class.set(wait: 20.seconds).perform_later(donation)
  end
end
