module JSONAPI::ResourceActions::Sideposting

def apply_resolved_relationships!(resource, resolved_relationships)

def apply_resolved_relationships!(resource, resolved_relationships)
  payload = { relationships: resolved_relationships }
  params_hash = JSONAPI::Deserializer.new(
    payload,
    model_class: resource.class,
    action: :update,
  ).to_model_attributes
  resource.update!(params_hash)
end

def build_resource_from_resolved_data(resolved_data)

def build_resource_from_resolved_data(resolved_data)
  sti_class = determine_sti_class
  params_hash, @create_attachments = prepare_create_params_from_data(sti_class, resolved_data)
  sti_class.new(params_hash)
end

def contains_lid?(rel_data)

def contains_lid?(rel_data)
  return false if rel_data.blank?
  if rel_data.is_a?(Array)
    rel_data.any? { |item| contains_lid?(item) }
  else
    (rel_data[:lid] || rel_data["lid"]).to_s.present?
  end
end

def create_with_sidepost

def create_with_sidepost
  if self.class.included_first?
    create_with_sidepost_included_first
  else
    create_with_sidepost_primary_first
  end
end

def create_with_sidepost_included_first

def create_with_sidepost_included_first
  ActiveRecord::Base.transaction do
    processor = JSONAPI::Sideposting::Processor.new(included: params[:included], controller: self)
    processor.create_all!
    resolved_data = processor.lid_resolver.resolve(raw_jsonapi_data)
    resource = build_resource_from_resolved_data(resolved_data)
    authorize_resource_action!(resource, action: :create)
    attach_active_storage_files(resource, @create_attachments, resource_class: determine_sti_resource_class)
    save_created_with_sidepost(resource, processor.created_records)
  end
end

def extract_lid_relationships!(data)

def extract_lid_relationships!(data)
  extracted = {}
  rels = data[:relationships] || {}
  rels.each do |key, val|
    next unless val.is_a?(Hash)
    d = val[:data] || val["data"]
    next unless contains_lid?(d)
    extracted[key] = val
  end
  extracted.each_key { |k| rels.delete(k) }
  extracted
end

def included_first?

def included_first?
  sidepost_order_value == JSONAPI::Sideposting::Order::INCLUDED_FIRST
end

def sidepost_order(value)

def sidepost_order(value)
  order = value.to_sym
  unless JSONAPI::Sideposting::Order::VALID_ORDERS.include?(order)
    raise ArgumentError, "sidepost_order must be one of #{JSONAPI::Sideposting::Order::VALID_ORDERS.join(", ")}"
  end
  @sidepost_order = order
end

def sidepost_order_value

def sidepost_order_value
  @sidepost_order || JSONAPI::Sideposting::Order::PRIMARY_FIRST
end

def sidepost_request?

def sidepost_request?
  params[:included].present?
end