require 'test_helper'

class NotificationsControllerTest < ActionController::TestCase
  include Devise::Test::ControllerHelpers

  test 'should get index as JSON' do
    sign_in users(:standard_user)

    [:json, :html].each do |format|
      try_index(format: format)

      assert_response(:success)

      if format == :html
        @notifications = assigns(:notifications)
        assert_not_nil @notifications
      else
        assert_valid_json_response
        notifications = JSON.parse(response.body)

        notifications.each do |notification|
          assert notification['content'].present?
          assert notification['community_name'].present?
        end

      end
    end
  end

  test 'should mark notification as read' do
    sign_in users(:standard_user)
    post :read, params: { id: notifications(:one).id, format: :json }
    assert_not_nil assigns(:notification)
    assert_equal true, assigns(:notification).is_read
    assert_equal 'success', JSON.parse(response.body)['status']
    assert_response(:success)
  end

  test 'should mark all notifications as read' do
    sign_in users(:standard_user)
    post :read_all, params: { format: :json }
    assert_not_nil assigns(:notifications)
    assigns(:notifications).each do |notification|
      assert_equal true, notification.is_read
    end
    assert_equal 'success', JSON.parse(response.body)['status']
    assert_response(:success)
  end

  test 'should prevent users marking others notifications read' do
    sign_in users(:editor)
    post :read, params: { id: notifications(:one).id, format: :json }
    assert_response(:forbidden)
  end

  test 'should require authentication to get index' do
    sign_out :user
    get :index, params: { format: :json }
    assert_response(:unauthorized) # Devise seems to respond 401 for JSON requests.
  end

  private

  def try_index(format: :json)
    get :index, params: { format: format }
  end
end
