defmodule AprsmeWeb.UserConfirmationInstructionsLiveTest do
  use AprsmeWeb.ConnCase

  import Aprsme.AccountsFixtures
  import Phoenix.LiveViewTest

  alias Aprsme.Accounts
  alias Aprsme.Repo

  describe "Resend confirmation instructions page" do
    test "renders the page", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/users/confirm", on_error: :warn)

      assert html =~ "Resend confirmation instructions"
      assert html =~ "Log in"
      assert html =~ "Register"
    end
  end

  describe "Resend confirmation" do
    setup do
      %{user: user_fixture()}
    end

    test "sends a new confirmation token for an unconfirmed user", %{conn: conn, user: user} do
      {:ok, lv, _html} = live(conn, ~p"/users/confirm", on_error: :warn)

      {:ok, conn} =
        lv
        |> form("#resend_confirmation_form", user: %{email: user.email})
        |> render_submit()
        |> follow_redirect(conn, "/")

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "If your email is in our system"

      assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "confirm"
    end

    test "does not send confirmation token for unknown email", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/users/confirm", on_error: :warn)

      {:ok, conn} =
        lv
        |> form("#resend_confirmation_form", user: %{email: "unknown@example.com"})
        |> render_submit()
        |> follow_redirect(conn, "/")

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "If your email is in our system"
      assert Repo.all(Accounts.UserToken) == []
    end
  end
end
