defmodule BerrypodWeb.SetupController do
  use BerrypodWeb, :controller

  alias Berrypod.Accounts
  alias BerrypodWeb.UserAuth

  @doc """
  Logs in a user via a setup login token.

  The setup wizard generates a token after creating the admin account,
  then redirects here to set the session cookie (LiveViews can't do that).
  """
  def login(conn, %{"token" => token}) do
    # Validate token first — login_user_by_magic_link crashes on invalid base64
    if Accounts.get_user_by_magic_link_token(token) do
      case Accounts.login_user_by_magic_link(token) do
        {:ok, {user, tokens_to_disconnect}} ->
          UserAuth.disconnect_sessions(tokens_to_disconnect)

          conn
          |> put_session(:user_return_to, ~p"/setup")
          |> UserAuth.log_in_user(user)

        _ ->
          login_failed(conn)
      end
    else
      login_failed(conn)
    end
  end

  @doc """
  Logs in after a successful password recovery.

  Uses get_user_by_magic_link_token directly instead of login_user_by_magic_link,
  because the latter raises for users with a password set (which recovery just did).
  """
  def recover_login(conn, %{"token" => token}) do
    case Accounts.get_user_by_magic_link_token(token) do
      %Accounts.User{} = user ->
        conn
        |> put_session(:user_return_to, ~p"/admin")
        |> UserAuth.log_in_user(user)

      _ ->
        recover_login_failed(conn)
    end
  end

  defp login_failed(conn) do
    conn
    |> put_flash(:error, "Login failed — please try again.")
    |> redirect(to: ~p"/setup")
  end

  defp recover_login_failed(conn) do
    conn
    |> put_flash(:error, "Recovery login failed — please try again.")
    |> redirect(to: ~p"/recover")
  end
end
