# frozen_string_literal: true

require 'rails_helper'

RSpec.describe Api::UsersController, type: :controller do
  before do
    ENV['CUSTOM_API_TOKEN'] = "custom_token"
  end
  describe '#create' do
    context 'Invalid token' do
      it 'Returns 401 (Unauthorized) status if token is not valid' do

        post :create

        expect(response).not_to be_successful
        expect(response).to have_http_status(401)
      end
    end

    context 'Valid token' do
      before :each do
        controller.request.env['HTTP_AUTHORIZATION'] = 'Bearer custom_token'
      end

      it 'Returns Server error if user param is missing' do
        user_count = User.all.count

        expect do
          post :create
        end.to raise_exception ActionController::ParameterMissing

        expect(User.all.count).to eq user_count
      end

      it 'Returns Server Error if email or password is missing' do
        user_count = User.all.count

        expect do
          post :create, params: { user: { email: "a@b.com" } }
        end.to raise_exception ActionController::ParameterMissing

        expect do
          post :create, params: { user: { password: "123" } }
        end.to raise_exception ActionController::ParameterMissing

        expect(User.all.count).to eq user_count
      end

      it 'Returns Server Error if body contains not permitted params' do
        user_count = User.all.count

        expect do
          post :create, params: { user: { email: "a@b.com", password: "123", admin: true } }
        end.to raise_exception ActionController::UnpermittedParameters

        expect(User.all.count).to eq user_count
      end

      it 'Creates user if body contains correct params' do
        expect do
          post :create, params: { user: { email: "a@b.com", password: "123" } }
        end.to change(User, :count).by(1)

        expect(response).to be_successful
      end

      it 'Nothing changes if existing email is used' do
        create(:user, email: "a@b.com")

        expect do
          post :create, params: { user: { email: "a@b.com", password: "123" } }
        end.not_to change(User, :count)

        expect(response).to be_successful
      end
    end
  end
end
