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

  layout false

  def show
    resource = params[:resource]

    if resource && resource.match(/acct:\w+/)
      useraddress = resource.split(":").last
      username, org = useraddress.split("@")
      username.downcase!
      unless User.where(cn: username, ou: org).any?
        head 404 and return
      end

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

  private

  def webfinger(useraddress)
    links = [];

    links << remotestorage_link(useraddress) if Setting.remotestorage_enabled

    { "links" => links }
  end

  def remotestorage_link(useraddress)
    # TODO use when OAuth routes are available
    # auth_url = new_rs_oauth_url(useraddress)
    auth_url = "https://example.com/rs/oauth"
    storage_url = "#{Setting.rs_storage_url}/#{useraddress}"

    {
      "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
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
  end
end
