module HasAttachments
  extend ActiveSupport::Concern

  included do
    has_many :attachments, -> { order :position }, dependent: :destroy, as: :attachable_for, class_name: "Attachment"
    has_many :assets, through: :attachments

    has_many :assets,
              through: :attachments,
              source: :asset

    # has_many :images,
    #         -> { with_attached_file.where('assets.content_type LIKE ?', "image/%") },
    #         through: :attachments,
    #         source: :asset
    #
    # has_many :images_favorites_first,
    #         -> { with_attached_file.where('assets.content_type LIKE ?', "image/%").reorder('attachments.is_favorite DESC', 'attachments.position ASC') },
    #         through: :attachments,
    #         source: :asset


    accepts_nested_attributes_for :attachments, allow_destroy: true
  end


  def icon
    assets.find { |a| a.file.attached? && a.file.content_type&.start_with?("image/") }
  end
end
