defmodule ToweropsWeb.Admin.OrgLive.Index do
  @moduledoc """
  Admin interface for viewing and managing organizations.
  """
  use ToweropsWeb, :live_view

  alias Towerops.Admin

  @impl true
  def mount(_params, _session, socket) do
    orgs = Admin.list_all_organizations()

    {:ok,
     socket
     |> assign(:page_title, "All Organizations")
     |> assign(:timezone, socket.assigns.current_scope.timezone)
     |> assign(:organizations, orgs)}
  end

  @impl true
  def handle_event("delete_org", %{"id" => org_id}, socket) do
    superuser = socket.assigns.current_scope.superuser || socket.assigns.current_scope.user
    ip = get_connect_info_ip(socket)

    case Admin.delete_organization(org_id, superuser.id, ip) do
      {:ok, _} ->
        {:noreply,
         socket
         |> put_flash(:info, t_admin("Organization deleted successfully"))
         |> assign(:organizations, Admin.list_all_organizations())}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, t_admin("Failed to delete organization"))}
    end
  end

  defp get_connect_info_ip(socket) do
    case get_connect_info(socket, :peer_data) do
      %{address: address} -> to_string(:inet_parse.ntoa(address))
      _ -> "unknown"
    end
  end
end
