require 'rails_helper'

RSpec.describe 'remoteStorage OAuth Dialog', type: :feature do
  context "when signed in" do
    let(:user) { create :user }

    before do
      login_as user, :scope => :user
    end

    context "with normal permissions" do
      before do
        visit new_rs_oauth_path(username: user.cn,
                                redirect_uri: "http://example.com",
                                client_id: "http://example.com",
                                scope: "documents,[photos], contacts:r")
      end

      it "shows the permissions in a list" do
        within ".permissions" do
          expect(page).to have_content("documents")
          expect(page).to have_content("photos")
          expect(page).to have_content("contacts")
        end

        within ".scope:first-of-type" do
          expect(page).not_to have_content("read only")
        end

        within ".scope:last-of-type" do
          expect(page).to have_content("read only")
        end
      end
    end

    context "root access" do
      context "full" do
        before do
          visit new_rs_oauth_path(username: user.cn,
                                  redirect_uri: "http://example.com",
                                  client_id: "http://example.com",
                                  scope: ":rw")
        end

        it "shows a special permission for all files and dirs" do
          within ".scope" do
            expect(page).to have_content("All files and directories")
          end
        end
      end
    end
  end

  context "when signed out" do
    let(:user) { create :user }

    before do
      allow_any_instance_of(User).to receive(:valid_ldap_authentication?)
        .with(user.password).and_return(true)
    end

    it "prefills the username field in the signin form" do
      visit new_rs_oauth_path(username: user.cn,
                              redirect_uri: "http://example.com",
                              client_id: "http://example.com",
                              scope: "documents,[photos], contacts:r")

      expect(find("#user_cn").value).to eq(user.cn)
    end

    it "redirects to the OAuth dialog after sign-in" do
      auth_url = new_rs_oauth_url(username: user.cn,
                                   redirect_uri: "http://example.com",
                                   client_id: "http://example.com",
                                   scope: "documents,[photos], contacts:r")
      visit auth_url

      fill_in "User", with: user.cn
      fill_in "Password", with: user.password
      click_button "Log in"

      expect(current_url).to eq(auth_url)
    end
  end
end
