defmodule BerrypodWeb.AccountController do
  @moduledoc """
  Handles account-related session operations that can't be done in LiveView.

  These routes manage TOTP setup state in the session, which persists across
  LiveView reconnects on mobile devices.
  """
  use BerrypodWeb, :controller

  alias Berrypod.Accounts

  @doc """
  Starts TOTP setup by generating a secret and storing it in the session.
  The session persists across LiveView reconnects.
  """
  def start_totp_setup(conn, _params) do
    user = conn.assigns.current_scope.user

    unless Accounts.sudo_mode?(user) do
      conn
      |> put_flash(:error, "Please log in again to enable 2FA.")
      |> redirect(to: ~p"/users/log-in?return_to=/admin/account")
    else
      {secret, _uri} = Accounts.generate_totp_secret(user)

      conn
      |> put_session(:totp_setup_secret, secret)
      |> redirect(to: ~p"/admin/account")
    end
  end

  @doc """
  Clears the TOTP setup session state.
  """
  def cancel_totp_setup(conn, _params) do
    conn
    |> delete_session(:totp_setup_secret)
    |> redirect(to: ~p"/admin/account")
  end

  @doc """
  Clears the TOTP setup session and stores backup codes for display.
  Called via redirect from the LiveView after successful enablement.
  """
  def complete_totp_setup(conn, %{"codes" => codes_param}) do
    # Codes come as comma-separated string
    backup_codes = String.split(codes_param, ",")

    conn
    |> delete_session(:totp_setup_secret)
    |> put_session(:totp_backup_codes, backup_codes)
    |> redirect(to: ~p"/admin/account")
  end

  @doc """
  Clears the backup codes from the session after user confirms they've saved them.
  """
  def clear_backup_codes(conn, _params) do
    conn
    |> delete_session(:totp_backup_codes)
    |> redirect(to: ~p"/admin/account")
  end
end
