defmodule ToweropsWeb.DebugControllerTest do
  use ToweropsWeb.ConnCase, async: true

  import Towerops.AccountsFixtures
  import Towerops.OrganizationsFixtures

  describe "GET /admin/headers" do
    test "returns headers JSON for superuser", %{conn: conn} do
      superuser =
        user_fixture()
        |> Ecto.Changeset.change(%{is_superuser: true})
        |> Towerops.Repo.update!()

      _org = organization_fixture(superuser.id)

      conn =
        conn
        |> log_in_user(superuser)
        |> get(~p"/admin/headers")

      response = json_response(conn, 200)

      assert Map.has_key?(response, "headers")
      assert Map.has_key?(response, "remote_ip")
      assert Map.has_key?(response, "request_path")
      assert Map.has_key?(response, "method")

      assert is_map(response["headers"])
      assert is_binary(response["remote_ip"])
      assert response["request_path"] == "/admin/headers"
      assert response["method"] == "GET"
    end

    test "non-superuser is redirected", %{conn: conn} do
      user = user_fixture()
      _org = organization_fixture(user.id)

      conn =
        conn
        |> log_in_user(user)
        |> get(~p"/admin/headers")

      assert redirected_to(conn) == ~p"/orgs"
    end

    test "unauthenticated user is redirected to login", %{conn: conn} do
      conn = get(conn, ~p"/admin/headers")

      assert redirected_to(conn) == ~p"/users/log-in"
    end
  end
end
