class Library < ApplicationRecord
  include AASM

  belongs_to :user
  belongs_to :cover, class_name: 'Attachment', foreign_key: :cover_id, optional: true

  has_many :library_applies, dependent: :delete_all
  has_many :library_library_tags, dependent: :delete_all
  has_many :library_tags, through: :library_library_tags

  has_many :attachments, as: :container
  has_one :praise_tread_cache, foreign_key: :object_id

  validates :uuid, presence: true, uniqueness: true

  aasm(:status) do
    state :pending, initiali: true
    state :processing
    state :refused
    state :published

    event :submit do
      transitions from: [:pending, :refused], to: :processing
    end

    event :refuse do
      transitions from: :processing, to: :refused
    end

    event :publish do
      transitions from: :processing, to: :published
    end
  end

  def generate_uuid
    uuid = Util::UUID.time_uuid
    while Library.exists?(uuid: uuid)
      uuid = Util::UUID.time_uuid
    end

    self.uuid = uuid
  end
end