module Signable
  extend ActiveSupport::Concern

  included do
    include ActiveStorageSupport::SupportForBase64

    has_one_base64_attached :signature

    scope :having_a_signature,  -> { left_joins(:signature_attachment).group(:id).having("COUNT(active_storage_attachments) > 0") }
    scope :having_no_signature, -> { left_joins(:signature_attachment).group(:id).having("COUNT(active_storage_attachments) = 0") }

    # Create some descriptive aliases for scopes above relating to native vs. non-native
    scope :native,      -> { having_a_signature }
    scope :non_native,  -> { having_no_signature }
  end

  def native?
    signature.attached?
  end

  def signature_base64
    return nil
  end

  def signature_base64=(data_uri)
    return if data_uri.blank?

    signature.attach(data: data_uri, filename: "signature.png", content_type: "image/png", identify: "false")
  end
end
