require "rails_helper"

RSpec.describe ProfilesController, type: :controller do
  render_views

  let(:current_user) { create(:user) }

  before do
    sign_in current_user
  end

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

      expect(response).to be_successful
    end

    it "renders content" do
      get :show

      expect(response.body).to have_content(current_user.primary_account.name)
      expect(response.body).to have_content "Account Manager"
    end

    it "renders form for updating first, last name and time zone" do
      get :show

      expect(response.body).to have_content("First name")
      expect(response.body).to have_content("Last name")
      expect(response.body).to have_content("Time zone")
    end
  end

  describe "#update" do
    it "responds with redirect" do
      patch :update, params: { user: user_params }

      expect(response).to be_redirect
      expect(flash.notice).not_to be_nil
    end

    it "updates user's first and last name" do
      patch :update, params: { user: user_params }

      expect(current_user.first_name).to eq("John")
      expect(current_user.last_name).to eq("Doe")
      expect(current_user.full_name).to eq("John Doe")
      expect(response).to be_redirect
      expect(flash.notice).not_to be_nil
    end

    it "updates user's avatar" do
      patch :update, params: { user: user_params_with_avatar }

      expect(current_user.first_name).to eq("John")
      expect(current_user.last_name).to eq("Doe")
      expect(current_user.full_name).to eq("John Doe")
      expect(current_user.avatar.filename).to eq("person_photo.png")
      expect(current_user.avatar.signed_id).not_to be_nil
      expect(response).to be_redirect
      expect(flash.notice).not_to be_nil
    end

    it "updates user's time zone" do
      patch :update, params: { user: user_params }

      expect(current_user.time_zone).to eq("Berlin")
      expect(response).to be_redirect
      expect(flash.notice).not_to be_nil
    end
  end

  private

  def user_params
    { first_name: "John", last_name: "Doe", time_zone: "Berlin" }
  end

  def user_params_with_avatar
    avatar = Rack::Test::UploadedFile.new(file_fixture("person_photo.png"), "image/png")

    user_params.merge({ avatar: avatar })
  end
end
