# frozen_string_literal: true

# Persist roles on their holder
module BrainzRolePersistable
  extend ActiveSupport::Concern

  def persist_roles
    persist_artist_roles
    persist_company_roles
  end

  private

  def persist_artist_roles
    blueprint.artist_backward_relations&.each do |relation|
      role = subject.artist_roles.create!(
        artist: persist_shallow_artist(blueprint: relation.artist),
        role:   persist_role(blueprint: relation)
      )

      persist_details_of(relation, role)
    end
  end

  def persist_company_roles
    blueprint.label_backward_relations&.each do |relation|
      role = subject.company_roles.create!(
        company: persist_company(code: relation.label.id),
        role:    persist_role(blueprint: relation)
      )

      persist_details_of(relation, role)
    end
  end

  def persist_details_of(relation, role)
    attributes = relation.attributes || return

    attributes.each do |attr|
      string_attr = attr.is_a?(String) ? attr : attr.__content__
      role.details.find_or_create_by_name(string_attr)
    end
  end
end
