defmodule WhoNeedHelpWeb.UserSessionControllerTest do
  use WhoNeedHelpWeb.ConnCase, async: false

  import WhoNeedHelp.AccountsFixtures
  import Swoosh.TestAssertions
  alias WhoNeedHelp.Accounts

  setup do
    %{unconfirmed_user: unconfirmed_user_fixture(), user: user_fixture()}
  end

  describe "GET /users/log-in" do
    test "renders login page", %{conn: conn} do
      conn = get(conn, ~p"/users/log-in")
      response = html_response(conn, 200)
      assert get_resp_header(conn, "cache-control") == ["no-store"]
      assert response =~ "Log in"
      assert response =~ ~p"/users/register"
      assert response =~ "Email me a sign-in link"
      assert response =~ "Sign in with Google"
      assert response =~ "Use a password instead"
      assert response =~ ~s(id="magic-link-fragment-form")
      assert response =~ ~s(hidden)
    end

    test "renders login page with email filled in (sudo mode)", %{conn: conn, user: user} do
      html =
        conn
        |> log_in_user(user)
        |> get(~p"/users/log-in")
        |> html_response(200)

      assert html =~ "You need to reauthenticate"
      refute html =~ "Register"
      assert html =~ "Email me a sign-in link"

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

    test "renders login page (email + password)", %{conn: conn} do
      conn = get(conn, ~p"/users/log-in?mode=password")
      response = html_response(conn, 200)
      assert response =~ "Log in"
      assert response =~ ~p"/users/register"
      assert response =~ "Email me a sign-in link"
    end
  end

  describe "POST /users/log-in - email and password" do
    test "logs the user in", %{conn: conn, user: user} do
      user = set_password(user)

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"email" => user.email, "password" => valid_user_password()}
        })

      token = get_session(conn, :user_token)
      assert token

      assert get_session(conn, :live_socket_id) ==
               WhoNeedHelpWeb.UserAuth.live_socket_id(token)

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

      # Now do a logged in request and assert on the menu
      conn = get(conn, ~p"/")
      response = html_response(conn, 200)
      assert response =~ user.email
      assert response =~ ~p"/users/settings"
      assert response =~ ~p"/users/log-out"
    end

    test "logs the user in with remember me", %{conn: conn, user: user} do
      user = set_password(user)

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{
            "email" => user.email,
            "password" => valid_user_password(),
            "remember_me" => "true"
          }
        })

      assert conn.resp_cookies["_who_need_help_web_user_remember_me"]
      assert redirected_to(conn) == ~p"/"
    end

    test "logs the user in with return to", %{conn: conn, user: user} do
      user = set_password(user)

      conn =
        conn
        |> init_test_session(user_return_to: "/foo/bar")
        |> post(~p"/users/log-in", %{
          "user" => %{
            "email" => user.email,
            "password" => valid_user_password()
          }
        })

      assert redirected_to(conn) == "/foo/bar"
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Welcome back!"
    end

    test "emits error message with invalid credentials", %{conn: conn, user: user} do
      conn =
        post(conn, ~p"/users/log-in?mode=password", %{
          "user" => %{"email" => user.email, "password" => "invalid_password"}
        })

      response = html_response(conn, 200)
      assert response =~ "Log in"
      assert response =~ "Invalid email or password"
    end

    test "does not log in a suspended user with a valid password", %{conn: conn, user: user} do
      user = set_password(user)

      {:ok, user} =
        user
        |> Ecto.Changeset.change(moderation_status: :suspended)
        |> WhoNeedHelp.Repo.update()

      conn =
        post(conn, ~p"/users/log-in?mode=password", %{
          "user" => %{"email" => user.email, "password" => valid_user_password()}
        })

      refute get_session(conn, :user_token)
      assert html_response(conn, 200) =~ "Invalid email or password"
    end

    test "applies the configured password-login throttle", %{conn: conn, user: user} do
      previous = Application.get_env(:who_need_help, :rate_limit_policies)

      Application.put_env(:who_need_help, :rate_limit_policies, %{
        "password_login_email" => %{"limit" => 1, "window_seconds" => 60}
      })

      on_exit(fn -> Application.put_env(:who_need_help, :rate_limit_policies, previous) end)

      params = %{"user" => %{"email" => user.email, "password" => "invalid_password"}}

      assert conn |> post(~p"/users/log-in", params) |> html_response(200) =~
               "Invalid email or password"

      throttled = post(build_conn(), ~p"/users/log-in", params)
      assert throttled.status == 429
      assert html_response(throttled, 429) =~ "Too many sign-in attempts"
    end

    test "authenticated responses are not stored", %{conn: conn, user: user} do
      conn =
        conn
        |> log_in_user(user)
        |> get(~p"/users/settings")

      assert get_resp_header(conn, "cache-control") == ["no-store"]
    end
  end

  describe "POST /users/log-in - magic link" do
    test "returns bad request for malformed parameters", %{conn: conn} do
      conn = post(conn, ~p"/users/log-in", %{"user" => %{"email" => ["invalid"]}})

      assert html_response(conn, 400) =~ "The sign-in form is invalid."
      assert get_resp_header(conn, "cache-control") == ["no-store"]
    end

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

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"email" => user.email}
        })

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "If your email is in our system"
      assert WhoNeedHelp.Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "login"

      assert_email_sent(fn email ->
        email.text_body =~ "/users/log-in#token=" and
          not String.contains?(email.text_body, "/users/log-in/")
      end)
    end

    test "does not send a magic link for a suspended user", %{conn: conn, user: user} do
      {:ok, user} =
        user
        |> Ecto.Changeset.change(moderation_status: :suspended)
        |> WhoNeedHelp.Repo.update()

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"email" => user.email}
        })

      assert redirected_to(conn) == ~p"/users/log-in"
      refute WhoNeedHelp.Repo.get_by(Accounts.UserToken, user_id: user.id)
    end

    test "logs the user in", %{conn: conn, user: user} do
      {token, _hashed_token} = generate_user_magic_link_token(user)

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"token" => token}
        })

      assert get_session(conn, :user_token)
      assert redirected_to(conn) == ~p"/"

      # Now do a logged in request and assert on the menu
      conn = get(conn, ~p"/")
      response = html_response(conn, 200)
      assert response =~ user.email
      assert response =~ ~p"/users/settings"
      assert response =~ ~p"/users/log-out"
    end

    test "confirms unconfirmed user", %{conn: conn, unconfirmed_user: user} do
      {token, _hashed_token} = generate_user_magic_link_token(user)
      refute user.confirmed_at

      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"token" => token},
          "_action" => "confirmed"
        })

      assert get_session(conn, :user_token)
      assert redirected_to(conn) == ~p"/"
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "User confirmed successfully."

      assert Accounts.get_user!(user.id).confirmed_at

      # Now do a logged in request and assert on the menu
      conn = get(conn, ~p"/")
      response = html_response(conn, 200)
      assert response =~ user.email
      assert response =~ ~p"/users/settings"
      assert response =~ ~p"/users/log-out"
    end

    test "emits error message when magic link is invalid", %{conn: conn} do
      conn =
        post(conn, ~p"/users/log-in", %{
          "user" => %{"token" => "invalid"}
        })

      assert html_response(conn, 200) =~ "The link is invalid or it has expired."
    end
  end

  describe "DELETE /users/log-out" do
    test "logs the user out", %{conn: conn, user: user} do
      conn = conn |> log_in_user(user) |> delete(~p"/users/log-out")
      assert redirected_to(conn) == ~p"/"
      refute get_session(conn, :user_token)
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Logged out successfully"
    end

    test "succeeds even if the user is not logged in", %{conn: conn} do
      conn = delete(conn, ~p"/users/log-out")
      assert redirected_to(conn) == ~p"/"
      refute get_session(conn, :user_token)
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Logged out successfully"
    end
  end
end
