# frozen_string_literal: true

module SolidusKlarnaPayments
  class DiscountItemSerializer
    attr_reader :order

    def initialize(order)
      @order = order
    end

    def to_hash
      {
        type: "discount",
        quantity: 1,
        # send the name and the promo code
        name: name,
        reference: reference,
        total_amount: (@order.promo_total * 100).to_i,
        unit_price: (@order.promo_total * 100).to_i,
        tax_rate: 0,
        total_tax_amount: 0
      }
    end

    private

    def name
      @order.promotions.map(&:name).to_sentence
    end

    def reference
      if @order.promotions.first.respond_to?(:codes)
        @order.promotions.flat_map(&:codes).map(&:value).to_sentence
      else
        @order.promotions.map(&:code).to_sentence
      end
    end
  end
end

# frozen_string_literal: true

module SolidusKlarnaPayments
  class DiscountItemSerializer
    def initialize(order)
      @order = order
    end

    def to_hash
      {
        type: "discount",
        quantity: 1,
        # send the name and the promo code
        name: name,
        reference: reference,
        total_amount: (order.promo_total * 100).to_i,
        unit_price: (order.promo_total * 100).to_i,
        tax_rate: 0,
        total_tax_amount: 0
      }
    end

    private

    def name
      order.promotions.map(&:name).to_sentence
    end

    def reference
      order.all_adjustments.promotion.map do |promotion|
        promotion&.promotion_code&.value
      end.join(' ')
    end

    attr_reader :order
  end
end

Fix the discout item serializer reference
Fix the discout item serializer reference

Sending all the promotion codes to Klarna, we should
receive a 400 response since could be too long.

Send all the promotion codes is wrong because we should
send the used promotion code.

https://playground.us.portal.klarna.com/logs/detail/1261d539-7bd2-497d-9e6d-866ae22746c3
