class Library::Bib < ApplicationRecord
  audited

  attr_accessor :contributor_attributes

  belongs_to :school
  belongs_to :item_type
  belongs_to :publisher, optional: true

  has_many :holdings
  has_many :bib_contributors, autosave: true
  has_many :contributors, through: :bib_contributors

  validates :title, presence: true
  validates :title, :subtitle, length: { maximum: 128 }
  validates :isbn10, length: { maximum: 10 }
  validates :isbn13, length: { maximum: 13 }
  validates :lccn, length: { maximum: 12 }
  validates :page_count, :published_on, numericality: true, allow_nil: true

  before_validation :format_attributes

  before_save :set_bib_contributors

  scope :search_by_title, ->(term) { where('title LIKE ?', "%#{term}%") if term }
  scope :search_by_subtitle, ->(term) { where('subtitle LIKE ?', "%#{term}%") if term }
  scope :search_by_lccn, ->(lccn) { where('lccn LIKE ?', "%#{lccn}%") if lccn }

  scope :search_by_isbn, ->(isbn) do
    return unless isbn

    where('isbn10 LIKE ?', "%#{isbn}%").or(where('isbn13 LIKE ?', "%#{isbn}%"))
  end

  private
    def format_attributes
      self.isbn10 = isbn10.remove('-', ' ') if isbn10
      self.isbn13 = isbn13.remove('-', ' ') if isbn13
      self.lccn = lccn.remove('-', ' ') if lccn
    end

    def set_bib_contributors
      return if contributor_attributes.blank?

      contributor_attributes.each do |attributes|
        bib_contributor = bib_contributors.find_or_initialize_by(contributor_id: attributes[:id])
        bib_contributor.role = attributes[:role]
      end
    end
end
