defmodule WhoNeedHelpWeb.UserSettingsControllerTest do
  use WhoNeedHelpWeb.ConnCase, async: true

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

  setup :register_and_log_in_user

  describe "GET /users/settings" do
    test "renders settings page", %{conn: conn} do
      conn = get(conn, ~p"/users/settings")
      response = html_response(conn, 200)
      assert response =~ "Settings"
      assert response =~ ~s(id="update_password_username")
      assert response =~ ~s(autocomplete="username")
      assert response =~ "Google sign-in"
      assert response =~ "Connect Google account"
    end

    test "redirects if user is not logged in" do
      conn = build_conn()
      conn = get(conn, ~p"/users/settings")
      assert redirected_to(conn) == ~p"/users/log-in"
    end

    @tag token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
    test "redirects if user is not in sudo mode", %{conn: conn} do
      conn = get(conn, ~p"/users/settings")
      assert redirected_to(conn) == ~p"/users/log-in"

      assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
               "You must re-authenticate to access this page."
    end
  end

  describe "PUT /users/settings (change password form)" do
    test "updates the user password and resets tokens", %{conn: conn, user: user} do
      second_token = Accounts.generate_user_session_token(user)
      second_socket_id = WhoNeedHelpWeb.UserAuth.live_socket_id(second_token)
      :ok = WhoNeedHelpWeb.Endpoint.subscribe(second_socket_id)

      new_password_conn =
        put(conn, ~p"/users/settings", %{
          "action" => "update_password",
          "user" => %{
            "password" => "new valid password",
            "password_confirmation" => "new valid password"
          }
        })

      assert redirected_to(new_password_conn) == ~p"/users/settings"

      assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)

      assert Phoenix.Flash.get(new_password_conn.assigns.flash, :info) =~
               "Password updated successfully"

      assert_receive %Phoenix.Socket.Broadcast{event: "disconnect", topic: ^second_socket_id}
      refute Accounts.get_user_by_session_token(second_token)
      assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
    end

    test "does not update password on invalid data", %{conn: conn} do
      old_password_conn =
        put(conn, ~p"/users/settings", %{
          "action" => "update_password",
          "user" => %{
            "password" => "too short",
            "password_confirmation" => "does not match"
          }
        })

      response = html_response(old_password_conn, 200)
      assert response =~ "Settings"
      assert response =~ "should be at least 12 character(s)"
      assert response =~ "does not match password"
      refute response =~ ~s(value="too short")
      refute response =~ ~s(value="does not match")

      assert get_session(old_password_conn, :user_token) == get_session(conn, :user_token)
    end
  end

  describe "PUT /users/settings (change email form)" do
    test "returns bad request for malformed parameters", %{conn: conn} do
      conn = put(conn, ~p"/users/settings", %{"action" => "unknown"})

      assert html_response(conn, 400) =~ "The settings form is invalid."
    end

    @tag :capture_log
    test "updates the user email", %{conn: conn, user: user} do
      assert_email_sent()
      changed_email = unique_user_email()

      conn =
        put(conn, ~p"/users/settings", %{
          "action" => "update_email",
          "user" => %{"email" => changed_email}
        })

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

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~
               "A link to confirm your email"

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

      assert Accounts.get_user_by_email(user.email)
    end

    test "does not update email on invalid data", %{conn: conn} do
      conn =
        put(conn, ~p"/users/settings", %{
          "action" => "update_email",
          "user" => %{"email" => "with spaces"}
        })

      response = html_response(conn, 200)
      assert response =~ "Settings"
      assert response =~ "must have the @ sign and no spaces"
    end

    test "rate limits repeated email-change instructions", %{conn: conn} do
      previous = Application.get_env(:who_need_help, :rate_limit_policies)

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

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

      email = unique_user_email()
      params = %{"action" => "update_email", "user" => %{"email" => email}}

      assert redirected_to(put(conn, ~p"/users/settings", params)) == ~p"/users/settings"

      limited_conn = put(conn, ~p"/users/settings", params)
      response = html_response(limited_conn, 429)

      assert response =~ "Too many email-change requests"
    end
  end

  describe "POST /users/settings/confirm-email" do
    setup %{user: user} do
      email = unique_user_email()

      token =
        extract_user_token(fn url ->
          Accounts.deliver_user_update_email_instructions(%{user | email: email}, user.email, url)
        end)

      %{token: token, email: email}
    end

    test "updates the user email once", %{conn: conn, user: user, token: token, email: email} do
      page_conn = get(conn, ~p"/users/settings/confirm-email")
      page_response = html_response(page_conn, 200)
      assert page_response =~ ~s(id="email-change-fragment-form")
      assert page_response =~ ~s(hidden)

      conn = post(conn, ~p"/users/settings/confirm-email", %{"token" => token})
      assert redirected_to(conn) == ~p"/users/settings"

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~
               "Email changed successfully"

      refute Accounts.get_user_by_email(user.email)
      assert Accounts.get_user_by_email(email)

      conn = post(conn, ~p"/users/settings/confirm-email", %{"token" => token})

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

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

    test "does not update email with invalid token", %{conn: conn, user: user} do
      conn = post(conn, ~p"/users/settings/confirm-email", %{"token" => "oops"})
      assert redirected_to(conn) == ~p"/users/settings"

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

      assert Accounts.get_user_by_email(user.email)
    end

    test "does not update email without a token", %{conn: conn, user: user} do
      conn = post(conn, ~p"/users/settings/confirm-email", %{})
      assert redirected_to(conn) == ~p"/users/settings"

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

      assert Accounts.get_user_by_email(user.email)
    end

    test "does not raise when the token has a forged nested type", %{conn: conn, user: user} do
      conn =
        post(conn, ~p"/users/settings/confirm-email", %{
          "token" => %{"nested" => "value"}
        })

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

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

      assert Accounts.get_user_by_email(user.email)
    end

    test "redirects if user is not logged in", %{token: token} do
      conn = build_conn()
      conn = post(conn, ~p"/users/settings/confirm-email", %{"token" => token})
      assert redirected_to(conn) == ~p"/users/log-in"
    end

    @tag token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
    test "accepts a valid token outside sudo mode", %{
      conn: conn,
      token: token,
      email: email
    } do
      conn = post(conn, ~p"/users/settings/confirm-email", %{"token" => token})
      assert redirected_to(conn) == ~p"/users/settings"
      assert Accounts.get_user_by_email(email)
    end
  end
end
