class SaleOrder < ApplicationRecord
  self.primary_key = "sale_order_id"

  #primary key - need to be unique generated for multiple shops
  before_create :generate_sale_order_id

  belongs_to :sale
  belongs_to :order
  has_many :order_items, foreign_key: "order_id", primary_key: "order_id"

  def create_sale_order(sale_id, order_id)
      # sale_order = SaleOrder.new
      self.sale_id = sale_id
      self.order_id = order_id
      self.save!
  end

  def self.sync_sale_order_records(sale_orders)
    if !sale_orders.nil?
      sale_orders.each do |so|
        sale_order = SaleOrder.find_by_sale_order_id(so['sale_order_id'])
        # unless SaleOrder.exists?(so['sale_order_id'])
        if sale_order.nil?
          sale_order = SaleOrder.new
        end
        sale_order.sale_order_id = so['sale_order_id']
        sale_order.sale_id = so['sale_id']
        sale_order.order_id = so['order_id']
        sale_order.save
      end
      Rails.logger.debug '......... Sale Order sync completed ........'
    end
  end

  private
  def generate_sale_order_id
    # self.class.name
    if self.sale_order_id.nil?
      self.sale_order_id = SeedGenerator.generate_id(self.class.name, 'SOI')
    end

  end
end
