require "test_helper"

class Admin::UsersControllerTest < ActionDispatch::IntegrationTest
  test "should redirect to login when not authenticated" do
    get admin_users_path
    assert_redirected_to login_path
  end

  test "should redirect to root when logged in as non-admin" do
    login_as(users(:contributor_user))
    get admin_users_path
    assert_redirected_to root_path
  end

  test "should show users index when logged in as admin" do
    login_as(users(:admin_user))
    get admin_users_path
    assert_response :success
  end

  test "should get edit page for user when logged in as admin" do
    login_as(users(:admin_user))
    get edit_admin_user_path(users(:contributor_user))
    assert_response :success
  end

  test "should update user role when logged in as admin" do
    login_as(users(:admin_user))

    patch admin_user_path(users(:contributor_user)), params: {
      user: { role: "reviewer" }
    }

    assert_redirected_to admin_users_path
    assert_equal "reviewer", users(:contributor_user).reload.role
  end

  test "should delete user when logged in as admin" do
    login_as(users(:admin_user))

    # Delete reviewer_user who has no associated records
    assert_difference("User.count", -1) do
      delete admin_user_path(users(:reviewer_user))
    end

    assert_redirected_to admin_users_path
  end

  test "should not allow non-admin to update user" do
    login_as(users(:contributor_user))

    patch admin_user_path(users(:reviewer_user)), params: {
      user: { role: "admin" }
    }

    assert_redirected_to root_path
  end

  test "should not allow non-admin to delete user" do
    login_as(users(:contributor_user))

    assert_no_difference("User.count") do
      delete admin_user_path(users(:reviewer_user))
    end

    assert_redirected_to root_path
  end
end
