defmodule AprsmeWeb.UserConfirmationLiveTest do
  use AprsmeWeb.ConnCase

  import Aprsme.AccountsFixtures
  import Phoenix.LiveViewTest

  alias Aprsme.Accounts
  alias Aprsme.Repo

  setup do
    %{user: user_fixture()}
  end

  describe "Confirm user" do
    test "renders confirmation page", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/users/confirm/some-token", on_error: :warn)
      assert html =~ "Confirm your account"
    end

    test "confirms the given token once", %{conn: conn, user: user} do
      token =
        extract_user_token(fn url ->
          Accounts.deliver_user_confirmation_instructions(user, url)
        end)

      {:ok, lv, _html} = live(conn, ~p"/users/confirm/#{token}", on_error: :warn)

      result =
        lv
        |> form("#confirmation_form")
        |> render_submit()
        |> follow_redirect(conn, "/")

      assert {:ok, conn} = result
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "User confirmed successfully"

      assert Accounts.get_user!(user.id).confirmed_at
      refute conn.assigns[:current_user]
      assert Repo.all(Accounts.UserToken) == []

      # When not logged in a second confirmation attempt says the token is invalid
      {:ok, lv, _html} = live(conn, ~p"/users/confirm/#{token}", on_error: :warn)

      result =
        lv
        |> form("#confirmation_form")
        |> render_submit()
        |> follow_redirect(conn, "/")

      assert {:ok, conn} = result

      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
               "User confirmation link is invalid or it has expired"
    end

    test "does not confirm email with invalid token", %{conn: conn, user: user} do
      {:ok, lv, _html} = live(conn, ~p"/users/confirm/invalid-token", on_error: :warn)

      {:ok, conn} =
        lv
        |> form("#confirmation_form")
        |> render_submit()
        |> follow_redirect(conn, "/")

      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
               "User confirmation link is invalid or it has expired"

      refute Accounts.get_user!(user.id).confirmed_at
    end
  end
end
