require 'rails_helper'

describe Twitch::PlatformConnectionsController do
  include_context 'mocked permissions'

  let(:permission) { any_permission_in('users', 'twitch_user:update_details') }
  let(:user) { Twitch::User.new }
  let(:user_id) { 'somebody' }

  def fake_delete_response(success)
    Faraday::Response.new.tap do |response|
      allow(response)
        .to receive(:success?)
        .and_return(success)
    end
  end

  describe '#destroy' do
    before(:each) do
      allow(Twitch::User).to receive(:find).with(user_id).and_return(user)
    end

    describe 'permissions' do
      context 'a user with appropriate permissions (aka an admin)' do
        include_context 'an authorized user acting on a twitch user'
        include_context 'it creates any tracking call'

        before do
          allow(PlatformConnections::Connection)
            .to receive(:destroy)
            .and_return(fake_delete_response(true))
          delete :destroy, params: { user_id: user_id, platform: 'blizzard' }
        end

        it "deletes the user's connection to the specified platform" do
          expect(PlatformConnections::Connection).to have_received(:destroy).with(user_id, 'blizzard')
        end

        it 'shows a human readable platform name in the success message' do
          expect(flash[:success]).to eq 'Successfully deleted connection to Blizzard Battle.net.'
        end

        it_behaves_like 'it redirects the user and displays a success message'
      end

      context 'when the PlatformConnections service is unable to destroy the connection' do
        include_context 'an authorized user acting on a twitch user'

        before do
          allow(PlatformConnections::Connection)
            .to receive(:destroy)
            .and_return(fake_delete_response(false))
          delete :destroy, params: { user_id: user_id, platform: 'blizzard' }
        end

        it 'shows a human readable platform name in the success message' do
          expect(flash[:error]).to include 'Unable to delete connection to Blizzard Battle.net'
        end

        it_behaves_like 'it redirects the user and displays an error'
      end

      context 'a user without appropriate permissions' do
        include_context 'an unauthorized user acting on a twitch user'

        before do
          delete :destroy, params: { user_id: user_id, platform: 'blizzard' }
        end

        it_behaves_like 'it redirects the user and displays an error'
      end
    end
  end
end
