# frozen_string_literal: true

require_relative '../api_resource'

module ErpIntegration
  module Fulfil
    module Resources
      class SalesOrderLine < ApiResource
        self.model_name = 'sale.line'
        # Allows cancelling the entire sales order line in Fulfil.
        # @param id [Integer|String] The ID of the to be cancelled order line.
        # @return [boolean] Whether the sales order line was cancelled successfully or not.
        def cancel(id)
          client.put("model/sale.line/#{id}/cancel")
          true
        rescue ErpIntegration::HttpError::BadRequest
          false
        # Workaround: Fulfil api does not return a json when status code is 200 (a.k.a. "Ok")
        # and faraday is having an error when trying to parse it. Let's skip the parse error
        # and move on.
        rescue Faraday::ParsingError
          true
        end

        # Updates the sales order line quantity of canceled and non canceled items
        # @param sales_channel [Integer] Sales channel id
        # @param channel_identifier [String]
        # @param sku [String]
        # @param quantity [Integer] The total quantity (canceled + not canceled)
        #   Should be more or equal than quantity_canceled but the above criteria is suggested
        # @param quantity_canceled [Integer] the total quantity of canceled items (including new ones)
        # @return [boolean] Whether the sales order line was changed successfully or not.
        def adjust_quantity(sales_channel, channel_identifier,
                            sku, quantity, quantity_canceled)
          options = [{
            "channel_identifier": channel_identifier,
            "sale_lines":
              [{
                "sku": sku,
                "quantity": quantity,
                "quantity_canceled": quantity_canceled
              }]
          }]
          client.put("model/sale.channel/#{sales_channel}/create_order", options)
          true
        rescue ErpIntegration::HttpError::BadRequest
          false
        end
      end
    end
  end
end