require "tasks/sample_data/addressing"
require "tasks/sample_data/logging"

class PaymentMethodFactory
  include Logging
  include Addressing

  def create_samples(enterprises)
    log "Creating payment methods:"
    distributors = enterprises.select(&:is_distributor)
    distributors.each do |enterprise|
      create_payment_methods(enterprise)
    end
  end

  private

  def create_payment_methods(enterprise)
    return if enterprise.payment_methods.present?
    log "- #{enterprise.name}"
    create_cash_method(enterprise)
    create_card_method(enterprise)
  end

  def create_cash_method(enterprise)
    create_payment_method(
      enterprise,
      "Cash on collection",
      "Pay on collection!",
      Spree::Calculator::FlatRate.new
    )
  end

  def create_card_method(enterprise)
    create_payment_method(
      enterprise,
      "Credit card (fake)",
      "We charge 1%, but won't ask for your details. ;-)",
      Spree::Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 1)
    )
  end

  def create_payment_method(enterprise, name, description, calculator)
    card = enterprise.payment_methods.new(
      name: name,
      description: description,
      distributor_ids: [enterprise.id]
    )
    card.calculator = calculator
    card.save!
  end
end

require "tasks/sample_data/addressing"
require "tasks/sample_data/logging"

class PaymentMethodFactory
  include Logging
  include Addressing

  def create_samples(enterprises)
    log "Creating payment methods:"
    distributors = enterprises.select(&:is_distributor)
    distributors.each do |enterprise|
      create_payment_methods(enterprise)
    end
  end

  private

  def create_payment_methods(enterprise)
    return if enterprise.payment_methods.present?
    log "- #{enterprise.name}"
    create_cash_method(enterprise)
    create_card_method(enterprise)
  end

  def create_cash_method(enterprise)
    create_payment_method(
      enterprise,
      "Cash on collection",
      "Pay on collection!",
      Spree::Calculator::FlatRate.new
    )
  end

  def create_card_method(enterprise)
    create_payment_method(
      enterprise,
      "Credit card (fake)",
      "We charge 1%, but won't ask for your details. ;-)",
      Spree::Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 1)
    )
  end

  def create_payment_method(enterprise, name, description, calculator)
    card = enterprise.payment_methods.new(
      name: name,
      description: description,
      distributor_ids: [enterprise.id]
    )
    calculator.calculable = card
    calculator.save!
  end
end

Fix creation of sample payment methods on staging
Fix creation of sample payment methods on staging

Due to an unknown reason my chosen way of creating calculator and
assigning it to a payment method didn't work in staging environment even
though it was working in development.

Without diving deeper into the cause of this, I decided to change the
record assignments and fix the problem that way.
