# Duplicated from ActiveStorage::DirectUploadsController
# https://github.com/rails/rails/blob/v6.0.0/activestorage/app/controllers/active_storage/direct_uploads_controller.rb
class Api::DirectUploadsController < Api::ApiController
  include ActiveStorage::SetCurrent

  deserializable_resource :direct_upload, only: [:create]

  def create
    blob = ActiveStorage::Blob.create_before_direct_upload!(blob_params)
    render jsonapi: DirectUpload.new(blob)
  end

  private

  def blob_params
    params.
      require(:direct_upload).
      permit(:type, :filename, :byte_size, :checksum, :content_type, :metadata).
      except(:type).
      to_h.symbolize_keys
  end

  class DeserializableDirectUpload < JSONAPI::Deserializable::Resource
    attributes :filename, :byte_size, :checksum, :content_type, :metadata
  end

  class SerializableDirectUpload < JSONAPI::Serializable::Resource
    type 'direct_upload'

    attributes :id, :key, :signed_id, :url, :headers
  end

  class DirectUpload
    delegate :id, :key, :signed_id, to: :blob

    attr_reader :blob

    def initialize(blob)
      @blob = blob
    end

    def url
      blob.service_url_for_direct_upload 
    end

    def headers
      blob.service_headers_for_direct_upload
    end
  end
end
