require "rails_helper"

RSpec.describe SessionsController, type: :controller do
  render_views

  let(:user) { create(:user) }
  let(:account) { user.primary_account }

  describe "#new" do
    it "responds successfully" do
      get :new

      expect(response).to be_successful
    end

    it "renders the content" do
      get :new

      expect(response.body).to have_content("Sign In")
      expect(response.body).to have_field("Email")
      expect(response.body).to have_field("Password")
    end
  end

  describe "#create" do
    context "when sign in successful" do
      it "creates user_sign_in event" do
        expect {
          post :create, params: { session: { email: user.email, password: user.password_digest } }
        }.to have_enqueued_job(TrackAnalyticsJob).with(user, account, :track_user_sign_in, user_agent: "Rails Testing", user_ip: "0.0.0.0")
      end

      it "redirects to root" do
        post :create, params: { session: { email: user.email, password: user.password_digest } }

        expect(response).to redirect_to(signed_in_root_path)
      end

      context "when remember me true" do
        it "updates remember_created_at" do
          post :create, params: { session: { email: user.email, password: user.password_digest }, remember_me: 1 }

          expect(user.reload.remember_created_at).not_to be_nil
        end
      end

      context "when remember me not given" do
        it "does not save remember_me_created" do
          post :create, params: { session: { email: user.email, password: user.password_digest } }

          expect(user.reload.remember_created_at).to be_nil
        end
      end
    end

    context "when sign in not successful" do
      it "redirects to 'new_session_path'" do
        post :create, params: { session: { email: "bad_email@example.com", password: user.password_digest } }

        expect(response).to redirect_to(new_session_path)
      end

      it "displays a flash message" do
        post :create, params: { session: { email: "bad_email@example.com", password: user.password_digest } }

        expect(flash.alert).to eq t("sessions.create.alert")
      end
    end
  end

  describe "#destroy" do
    context "when user is signed in" do
      before :each do
        sign_in(user)
      end

      it "redirects to new_session_path" do
        delete :destroy, params: {}

        expect(response).to redirect_to(new_session_path)
      end
    end

    context "when user is not signed in" do
      it "renders session new" do
        delete :destroy, params: {}

        expect(response).to redirect_to(new_session_path)
      end
    end
  end
end
