class QrPaymentService
  attr_reader :sale_id, :current_login_employee, :sale, :booking, :processed_sale_payment

  def initialize(sale_id, current_login_employee)
    @sale_id = sale_id
    @current_login_employee = current_login_employee
  end

  def process
    return { status: false, message: "Sale ID is required." } unless sale_id.present?

    SalePayment.transaction do
      find_sale_and_booking
      return { status: false, message: "There is no sale for '#{sale_id}'!" } unless sale
      return { status: false, message: "Already paid for '#{sale_id}'!" } unless sale.sale_status == "new"

      status, payment_attempt = process_the_payment
      unless status
        error_message = payment_attempt&.errors&.full_messages&.join(', ') || "Payment processing failed."
        return { status: false, message: error_message }
      end

      process_orders_and_broadcast
      return { status: true, message: "Payment successful." }
    end
  rescue ActiveRecord::RecordNotFound
    { status: false, message: "Sale not found for ID '#{sale_id}'." }
  rescue StandardError => e
    Rails.logger.error "QrPaymentService Error: #{e.message}\n#{e.backtrace.join("\n")}"
    { status: false, message: "An unexpected error occurred: #{e.message}" }
  end

  private

  def find_sale_and_booking
    @sale = Sale.find_by_sale_id(sale_id) # Consider find_by_sale_id! if you want RecordNotFound earlier
    @booking = @sale&.booking
  end

  def process_the_payment
    sale_payment_creator = SalePayment.new
    status, payment = sale_payment_creator.process_payment(
      sale,
      current_login_employee,
      sale.grand_total,
      "MMQR".parameterize
    )
    [status, payment]
  end

  def process_orders_and_broadcast
    booking.orders.each do |order|
      oqs = OrderQueueStation.new
      oqs.pay_process_order_queue(order.order_id, booking.dining_facility_id)

      assign_order = AssignedOrderItem.assigned_order_item_by_job(order.order_id)
      ActionCable.server.broadcast "order_queue_station_channel", order: assign_order
    end
  end
end
