defmodule ZoeyscomputerWeb.ApiKeyLive.Show do
  use ZoeyscomputerWeb, :live_view

  alias Zoeyscomputer.ApiKeys

  @impl true
  def mount(_params, _session, socket) do
    if connected?(socket) do
      IO.puts("LiveView Connected")
    end

    {:ok, socket}
  end

  @impl true
  def handle_params(%{"id" => id}, _, socket) do
    api_key = ApiKeys.get_api_key!(id)

    # Ensure users can only view their own API keys
    if api_key.user_id == socket.assigns.current_user.id do
      {:noreply,
       socket
       |> assign(:page_title, "API Key Details")
       |> assign(:api_key, api_key)}
    else
      {:noreply,
       socket
       |> put_flash(:error, "Not authorized")
       |> push_navigate(to: ~p"/api-keys")}
    end
  end

  @impl true
  def handle_event("copy_token", _, socket) do
    IO.puts("Copy token event received")
    token = socket.assigns.api_key.token
    IO.puts("Token to copy: #{token}")
    {:noreply, push_event(socket, "copy", %{text: token})}
  end
end
