defmodule MicrowavepropWeb.UserManagementLiveTest do
  use MicrowavepropWeb.ConnCase

  import Microwaveprop.AccountsFixtures
  import Phoenix.LiveViewTest

  alias Microwaveprop.Accounts

  defp admin_user_fixture do
    user = user_fixture()
    {:ok, user} = Accounts.admin_update_user(user, %{is_admin: true})
    user
  end

  describe "Index" do
    test "redirects non-admin to /", %{conn: conn} do
      conn = log_in_user(conn, user_fixture())
      assert {:error, {:redirect, %{to: "/"}}} = live(conn, ~p"/users")
    end

    test "redirects anonymous user to log in", %{conn: conn} do
      assert {:error, {:redirect, %{to: "/users/log-in"}}} = live(conn, ~p"/users")
    end

    test "admin sees the user list", %{conn: conn} do
      admin = admin_user_fixture()
      other = user_fixture(callsign: "W5TX")
      conn = log_in_user(conn, admin)

      {:ok, _view, html} = live(conn, ~p"/users")
      assert html =~ admin.callsign
      assert html =~ other.callsign
    end

    test "admin can delete another user", %{conn: conn} do
      admin = admin_user_fixture()
      target = user_fixture(callsign: "W5TX")
      conn = log_in_user(conn, admin)

      {:ok, view, _} = live(conn, ~p"/users")

      render_click(view, "delete", %{"id" => target.id})
      refute Accounts.get_user_by_email(target.email)
    end
  end

  describe "Edit" do
    test "admin can promote a user to admin", %{conn: conn} do
      admin = admin_user_fixture()
      target = user_fixture(callsign: "W5TX")
      conn = log_in_user(conn, admin)

      {:ok, form_live, _} = live(conn, ~p"/users/#{target.id}/edit")

      assert {:ok, _view, _html} =
               form_live
               |> form("#user-form",
                 user: %{
                   callsign: target.callsign,
                   name: target.name,
                   email: target.email,
                   is_admin: true
                 }
               )
               |> render_submit()
               |> follow_redirect(conn, ~p"/users")

      assert Accounts.get_user!(target.id).is_admin
    end
  end
end
