defmodule ToweropsWeb.Admin.DashboardLiveTest do
  use ToweropsWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  setup do
    user = Towerops.AccountsFixtures.user_fixture()
    user = user |> Ecto.Changeset.change(%{is_superuser: true}) |> Towerops.Repo.update!()
    {:ok, _organization} = Towerops.Organizations.create_organization(%{name: "Test Org"}, user.id)

    token = Towerops.Accounts.generate_user_session_token(user)

    conn =
      build_conn()
      |> Phoenix.ConnTest.init_test_session(%{})
      |> Plug.Conn.put_session(:user_token, token)

    %{conn: conn, user: user}
  end

  describe "mount" do
    test "renders admin dashboard for superuser", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/admin")

      assert html =~ "Admin Dashboard"
    end

    test "shows user and org counts", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/admin")

      assert html =~ "Users"
      assert html =~ "Organizations"
    end

    test "redirects non-superuser to /orgs" do
      regular_user = Towerops.AccountsFixtures.user_fixture()
      token = Towerops.Accounts.generate_user_session_token(regular_user)

      conn =
        build_conn()
        |> Phoenix.ConnTest.init_test_session(%{})
        |> Plug.Conn.put_session(:user_token, token)

      assert {:error, {:redirect, %{to: "/orgs"}}} = live(conn, ~p"/admin")
    end
  end
end
