defmodule ToweropsWeb.DashboardLive do
  @moduledoc false
  use ToweropsWeb, :live_view

  alias Towerops.Alerts
  alias Towerops.Devices
  alias Towerops.Sites

  @impl true
  def mount(_params, _session, socket) do
    organization = socket.assigns.current_organization

    # Subscribe to real-time alert updates
    _ =
      if connected?(socket) do
        _ = Phoenix.PubSub.subscribe(Towerops.PubSub, "alerts:new")
        Phoenix.PubSub.subscribe(Towerops.PubSub, "alerts:resolved")
      end

    {:ok,
     socket
     |> assign(:page_title, organization.name)
     |> load_dashboard_data(organization.id)}
  end

  @impl true
  def handle_info({:new_alert, _device_id, _alert_type}, socket) do
    {:noreply, load_dashboard_data(socket, socket.assigns.current_organization.id)}
  end

  @impl true
  def handle_info({:alert_resolved, _device_id, _alert_type}, socket) do
    {:noreply, load_dashboard_data(socket, socket.assigns.current_organization.id)}
  end

  defp load_dashboard_data(socket, organization_id) do
    active_alerts = Alerts.list_organization_active_alerts(organization_id)
    sites_count = length(Sites.list_organization_sites(organization_id))
    devices = Devices.list_organization_devices(organization_id)

    devices_by_status =
      devices
      |> Enum.group_by(& &1.status)
      |> Map.new(fn {status, equip} -> {status, length(equip)} end)

    socket
    |> assign(:active_alerts, active_alerts)
    |> assign(:sites_count, sites_count)
    |> assign(:device_count, length(devices))
    |> assign(:device_up, Map.get(devices_by_status, :up, 0))
    |> assign(:device_down, Map.get(devices_by_status, :down, 0))
    |> assign(:device_unknown, Map.get(devices_by_status, :unknown, 0))
  end
end
