defmodule WhoNeedHelpWeb.UserSettingsController do
  use WhoNeedHelpWeb, :controller

  require Logger

  alias WhoNeedHelp.{Accounts, GoogleAuth}
  alias WhoNeedHelp.Trust.RateLimiter
  alias WhoNeedHelpWeb.UserAuth

  import WhoNeedHelpWeb.UserAuth, only: [require_sudo_mode: 2]

  plug :require_sudo_mode when action in [:edit, :update]
  plug :assign_email_and_password_changesets when action in [:edit, :update]

  def edit(conn, _params) do
    render(conn, :edit)
  end

  def update(conn, %{"action" => "update_email", "user" => user_params})
      when is_map(user_params) do
    user = conn.assigns.current_scope.user

    case Accounts.change_user_email(user, user_params) do
      %{valid?: true} = changeset ->
        new_email =
          changeset
          |> Ecto.Changeset.get_change(:email, "")
          |> String.trim()
          |> String.downcase()

        case RateLimiter.check(:email_change_email, new_email) do
          {:ok, _limit} ->
            deliver_email_change_instructions(conn, user, changeset)

          {:error, :rate_limited} ->
            conn
            |> put_status(:too_many_requests)
            |> put_flash(
              :error,
              gettext("Too many email-change requests in the configured time window.")
            )
            |> render(:edit)
        end

      changeset ->
        render(conn, :edit, email_changeset: %{changeset | action: :insert})
    end
  end

  def update(conn, %{"action" => "update_password", "user" => user_params})
      when is_map(user_params) do
    user = conn.assigns.current_scope.user

    case Accounts.update_user_password(user, user_params) do
      {:ok, {user, expired_tokens}} ->
        :ok = UserAuth.disconnect_sessions(expired_tokens)
        {:ok, _cleanup} = WhoNeedHelp.Tracking.stop_all_sessions(user.id)

        conn
        |> put_flash(:info, gettext("Password updated successfully."))
        |> put_session(:user_return_to, ~p"/users/settings")
        |> UserAuth.log_in_user(user)

      {:error, changeset} ->
        render(conn, :edit, password_changeset: changeset)
    end
  end

  def update(conn, _params) do
    conn
    |> put_status(:bad_request)
    |> put_flash(:error, gettext("The settings form is invalid."))
    |> render(:edit)
  end

  def confirm_email_page(conn, _params) do
    render(conn, :confirm_email)
  end

  def confirm_email(conn, %{"token" => token}) when is_binary(token) do
    case Accounts.update_user_email(conn.assigns.current_scope.user, token) do
      {:ok, _user} ->
        conn
        |> put_flash(:info, gettext("Email changed successfully."))
        |> redirect(to: ~p"/users/settings")

      {:error, _} ->
        conn
        |> put_flash(:error, gettext("Email change link is invalid or it has expired."))
        |> redirect(to: ~p"/users/settings")
    end
  end

  def confirm_email(conn, _params) do
    conn
    |> put_flash(:error, gettext("Email change link is invalid or it has expired."))
    |> redirect(to: ~p"/users/settings")
  end

  defp assign_email_and_password_changesets(conn, _opts) do
    user = conn.assigns.current_scope.user

    conn
    |> assign(:email_changeset, Accounts.change_user_email(user))
    |> assign(:password_changeset, Accounts.change_user_password(user))
    |> assign(:google_auth_enabled, GoogleAuth.enabled?())
    |> assign(:google_auth_connected, Accounts.google_auth_connected?(user))
  end

  defp deliver_email_change_instructions(conn, user, changeset) do
    case Accounts.deliver_user_update_email_instructions(
           Ecto.Changeset.apply_action!(changeset, :insert),
           user.email,
           &"#{url(~p"/users/settings/confirm-email")}#token=#{URI.encode_www_form(&1)}"
         ) do
      {:ok, _email} ->
        conn
        |> put_flash(
          :info,
          gettext("A link to confirm your email change has been sent to the new address.")
        )
        |> redirect(to: ~p"/users/settings")

      {:error, _reason} ->
        Logger.warning("Unable to send email-change instructions")

        conn
        |> put_flash(
          :error,
          gettext("The confirmation email could not be sent. Please try again.")
        )
        |> redirect(to: ~p"/users/settings")
    end
  end
end
