defmodule MvWeb.LiveUserAuth do
  @moduledoc """
  Helpers for authenticating users in LiveViews.
  """

  import Phoenix.Component
  use MvWeb, :verified_routes

  # This is used for nested liveviews to fetch the current user.
  # To use, place the following at the top of that liveview:
  # on_mount {MvWeb.LiveUserAuth, :current_user}
  def on_mount(:current_user, _params, session, socket) do
    return_to = session[:return_to]

    socket =
      socket
      |> assign(:return_to, return_to)
      |> AshAuthentication.Phoenix.LiveSession.assign_new_resources(session)

    {:cont, session, socket}
  end

  def on_mount(:live_user_optional, _params, _session, socket) do
    if socket.assigns[:current_user] do
      {:cont, socket}
    else
      {:cont, assign(socket, :current_user, nil)}
    end
  end

  def on_mount(:live_user_required, _params, session, socket) do
    socket = AshAuthentication.Phoenix.LiveSession.assign_new_resources(socket, session)

    case socket.assigns do
      %{current_user: %{} = user} ->
        {:cont, assign(socket, :current_user, user)}

      _ ->
        socket = Phoenix.LiveView.redirect(socket, to: ~p"/sign-in")
        {:halt, socket}
    end
  end

  def on_mount(:live_no_user, _params, session, socket) do
    # Set the locale for not logged in user (default from config, "de" in dev/prod).
    locale = session["locale"] || Application.get_env(:mv, :default_locale, "de")
    Gettext.put_locale(MvWeb.Gettext, locale)
    {:cont, assign(socket, :locale, locale)}

    if socket.assigns[:current_user] do
      {:halt, Phoenix.LiveView.redirect(socket, to: ~p"/")}
    else
      {:cont, assign(socket, :current_user, nil)}
    end
  end
end
