module Spina
  module Parts
    class Image < Base
      attr_json :image_id, :integer, default: nil
      attr_json :signed_blob_id, :string, default: nil
      attr_json :alt, :string, default: ""
      attr_json :filename, :string, default: ""

      attr_accessor :options

      def to_s
        alt.presence || filename.presence || Spina::Image.model_name.human
      end

      def content
        self
      end

      def svg?
        filename.end_with?(".svg")
      end

      def spina_image
        Spina::Image.find_by(id: image_id)
      end

      def present?
        signed_blob_id.present?
      end

      # Rails 7.1 started using 'expires_at', so we 
      # include both expires_in and expires_at for backwards
      # compatibility
      def signed_id(expires_at: nil, expires_in: nil)
        signed_blob_id
      end

      def variant(options)
        Spina::Parts::ImageVariant.new(self, options)
      end
    end
  end
end
