class WebfingerController < ApplicationController
  before_action :allow_cross_origin_requests, only: [:show]

  layout false

  def show
    resource = params[:resource]

    if resource && @useraddress = resource.match(/acct:(.+)/)&.[](1)
      @username, @org = @useraddress.split("@")

      unless Rails.env.development?
        # Allow different domains (e.g. localhost:3000) in development only
        head 404 and return unless @org == Setting.primary_domain
      end

      unless User.where(cn: @username.downcase, ou: Setting.primary_domain).any?
        head 404 and return
      end

      render json: webfinger.to_json,
             content_type: "application/jrd+json"
    else
      head 422 and return
    end
  end

  private

  def webfinger
    links = [];

    # TODO check if storage service is enabled for user, not just globally
    links << remotestorage_link if Setting.remotestorage_enabled

    { "links" => links }
  end

  def remotestorage_link
    auth_url = new_rs_oauth_url(@username)
    storage_url = "#{Setting.rs_storage_url}/#{@username}"

    {
      "rel" => "http://tools.ietf.org/id/draft-dejong-remotestorage",
      "href" => storage_url,
      "properties" => {
        "http://remotestorage.io/spec/version" => "draft-dejong-remotestorage-13",
        "http://tools.ietf.org/html/rfc6749#section-4.2" => auth_url,
        "http://tools.ietf.org/html/rfc6750#section-2.3" => nil, # access token via a HTTP query parameter
        "http://tools.ietf.org/html/rfc7233": "GET", # content range requests
        "http://remotestorage.io/spec/web-authoring": nil
      }
    }
  end

  def allow_cross_origin_requests
    return unless Rails.env.development?
    headers['Access-Control-Allow-Origin'] = "*"
    headers['Access-Control-Allow-Methods'] = "GET"
  end
end
