# frozen_string_literal: true

class ArtistCredit < ApplicationRecord
  has_many :names, class_name: 'ArtistCreditName'

  has_many :albums
  has_many :contributions
  has_many :memberships
  has_many :songs
  has_many :tracks

  # Finds an artist credit that matches a list of raw artist credit names.
  #
  # Each raw name should include the following attributes:
  #
  #   * `:artist_id`
  #   * `:position`
  #   * `:locale`
  #   * `:name`
  #   * `:separator`
  #   * `:default`
  #   * `:original`
  #
  # @param [Array<Hash<String, Object>>] raw_names
  # @return [ActiveRecord::Relation]
  def self.lookup(raw_names)
    scope = all

    # alias
    a = 'a'

    raw_names.each do |attrs|
      scope = scope.joins(<<-SQL)
        INNER JOIN artist_credit_names #{a}
          ON #{a}.artist_credit_id = artist_credits.id
      SQL

      scope = attrs.reduce(scope) do |s, (k, v)|
        s.where("#{a}.#{k} = ?", v)
      end

      a = a.next
    end

    scope
  end
end
