defmodule BerrypodWeb.Auth.LoginTest do
  use BerrypodWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  alias Berrypod.Mailer

  describe "login page" do
    setup do
      user_fixture()
      Mailer.mark_email_verified()
      :ok
    end

    test "renders login page", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/users/log-in")

      assert html =~ "Log in"
      assert html =~ "Log in with email"
    end
  end

  describe "user login - magic link" do
    setup do
      Mailer.mark_email_verified()
      :ok
    end

    test "sends magic link email when user exists", %{conn: conn} do
      user = user_fixture()

      {:ok, lv, _html} = live(conn, ~p"/users/log-in")

      {:ok, _lv, html} =
        form(lv, "#login_form_magic", user: %{email: user.email})
        |> render_submit()
        |> follow_redirect(conn, ~p"/users/log-in")

      assert html =~ "If your email is in our system"

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

    test "does not disclose if user is registered", %{conn: conn} do
      user_fixture()

      {:ok, lv, _html} = live(conn, ~p"/users/log-in")

      {:ok, _lv, html} =
        form(lv, "#login_form_magic", user: %{email: "idonotexist@example.com"})
        |> render_submit()
        |> follow_redirect(conn, ~p"/users/log-in")

      assert html =~ "If your email is in our system"
    end
  end

  describe "user login - password" do
    test "redirects if user logs in with valid credentials", %{conn: conn} do
      user = user_fixture() |> set_password()

      {:ok, lv, _html} = live(conn, ~p"/users/log-in")

      form =
        form(lv, "#login_form_password",
          user: %{email: user.email, password: valid_user_password(), remember_me: true}
        )

      conn = submit_form(form, conn)

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

    test "redirects to login page with a flash error if credentials are invalid", %{
      conn: conn
    } do
      user_fixture()

      {:ok, lv, _html} = live(conn, ~p"/users/log-in")

      form =
        form(lv, "#login_form_password", user: %{email: "test@email.com", password: "123456"})

      render_submit(form, %{user: %{remember_me: true}})

      conn = follow_trigger_action(form, conn)
      assert Phoenix.Flash.get(conn.assigns.flash, :error) == "Invalid email or password"
      assert redirected_to(conn) == ~p"/users/log-in"
    end
  end

  describe "email not configured" do
    setup do
      original = Application.get_env(:berrypod, Berrypod.Mailer)
      Application.put_env(:berrypod, Berrypod.Mailer, adapter: Swoosh.Adapters.Local)
      on_exit(fn -> Application.put_env(:berrypod, Berrypod.Mailer, original) end)
      :ok
    end

    test "hides magic link form and shows recovery link", %{conn: conn} do
      _user = user_fixture()
      {:ok, _lv, html} = live(conn, ~p"/users/log-in")

      refute html =~ "Log in with email"
      assert html =~ "Locked out?"
      assert html =~ "Recover with setup secret"
    end
  end

  describe "email configured and verified" do
    setup do
      # Create user before switching adapter (fixture sends a confirmation email)
      _user = user_fixture()

      original = Application.get_env(:berrypod, Berrypod.Mailer)

      Application.put_env(:berrypod, Berrypod.Mailer,
        adapter: Swoosh.Adapters.Postmark,
        api_key: "test"
      )

      Mailer.mark_email_verified()

      on_exit(fn -> Application.put_env(:berrypod, Berrypod.Mailer, original) end)
      :ok
    end

    test "shows magic link form and hides recovery link", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/users/log-in")

      assert html =~ "Log in with email"
      refute html =~ "Locked out?"
    end
  end

  describe "email configured but not verified" do
    setup do
      # Create user before switching adapter (fixture sends a confirmation email)
      _user = user_fixture()

      original = Application.get_env(:berrypod, Berrypod.Mailer)

      Application.put_env(:berrypod, Berrypod.Mailer,
        adapter: Swoosh.Adapters.Postmark,
        api_key: "test"
      )

      Mailer.clear_email_verified()

      on_exit(fn -> Application.put_env(:berrypod, Berrypod.Mailer, original) end)
      :ok
    end

    test "hides magic link form and shows recovery link", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/users/log-in")

      refute html =~ "Log in with email"
      assert html =~ "Locked out?"
    end
  end

  describe "no admin exists" do
    test "redirects to setup", %{conn: conn} do
      assert {:error, {:redirect, %{to: "/setup"}}} = live(conn, ~p"/users/log-in")
    end
  end

  describe "re-authentication (sudo mode)" do
    setup %{conn: conn} do
      Mailer.mark_email_verified()
      user = user_fixture()
      %{user: user, conn: log_in_user(conn, user)}
    end

    test "shows login page with email filled in", %{conn: conn, user: user} do
      {:ok, _lv, html} = live(conn, ~p"/users/log-in")

      assert html =~ "You need to reauthenticate"
      refute html =~ "Register"
      assert html =~ "Log in with email"

      assert html =~
               ~s(<input type="email" name="user[email]" id="login_form_magic_email" value="#{user.email}")
    end
  end
end
