defmodule ToweropsWeb.UserSettingsLive.ApiTokenManager do
  @moduledoc """
  Handles API token management for user settings.
  """
  use Gettext, backend: ToweropsWeb.Gettext

  import ToweropsWeb.GettextHelpers

  alias Towerops.ApiTokens

  @doc """
  Creates a new API token for the user.
  """
  def create_api_token(socket, params) do
    user = socket.assigns.current_scope.user

    # Handle both nested token params and flat params
    {name, org_id} =
      case params do
        %{"token" => %{"name" => n, "organization_id" => o}} -> {n, o}
        %{"name" => n, "organization_id" => o} -> {n, o}
        _ -> {nil, nil}
      end

    if name && org_id do
      case ApiTokens.create_api_token(%{
             name: name,
             organization_id: org_id,
             user_id: user.id
           }) do
        {:ok, {_token, raw_token}} ->
          socket
          |> Phoenix.Component.assign(:show_add_token_modal, false)
          |> Phoenix.Component.assign(:created_token, raw_token)
          |> Phoenix.Component.assign(:show_token_modal, true)
          |> assign_api_tokens()

        {:error, _changeset} ->
          Phoenix.LiveView.put_flash(socket, :error, t_auth("Failed to create API token."))
      end
    else
      Phoenix.LiveView.put_flash(socket, :error, t_auth("Name and organization are required."))
    end
  end

  @doc """
  Closes the token display modal.
  """
  def close_token_modal(socket) do
    socket
    |> Phoenix.Component.assign(:show_token_modal, false)
    |> Phoenix.Component.assign(:created_token, nil)
  end

  @doc """
  Deletes an API token.
  """
  def delete_api_token(socket, token_id) do
    token = ApiTokens.get_api_token!(token_id)
    user = socket.assigns.current_scope.user

    if token.user_id == user.id do
      case ApiTokens.delete_api_token(token) do
        {:ok, _} ->
          socket
          |> Phoenix.LiveView.put_flash(:info, t_auth("API token deleted successfully."))
          |> assign_api_tokens()

        {:error, _} ->
          Phoenix.LiveView.put_flash(socket, :error, t_auth("Failed to delete API token."))
      end
    else
      Phoenix.LiveView.put_flash(socket, :error, t_auth("You can only delete your own tokens."))
    end
  end

  @doc """
  Assigns API tokens to socket.
  """
  def assign_api_tokens(socket) do
    user = socket.assigns.current_scope.user
    Phoenix.Component.assign(socket, :api_tokens, ApiTokens.list_user_api_tokens(user.id))
  end
end
