defmodule ToweropsWeb.AgentLive.Show do
  @moduledoc false
  use ToweropsWeb, :live_view

  import ToweropsWeb.AgentLive.Helpers

  alias Towerops.Agents

  @impl true
  def mount(%{"id" => id}, _session, socket) do
    organization = socket.assigns.current_organization
    agent_token = Agents.get_agent_token!(id)

    # Verify the agent belongs to this organization
    if agent_token.organization_id != organization.id do
      raise Ecto.NoResultsError
    end

    # device this agent is responsible for)
    polling_targets = Agents.list_agent_polling_targets(agent_token.id)

    # Get direct assignments
    direct_assignments = Agents.count_assigned_devices(agent_token.id)

    {:ok,
     socket
     |> assign(:page_title, agent_token.name)
     |> assign(:agent_token, agent_token)
     |> assign(:polling_targets, polling_targets)
     |> assign(:direct_assignments, direct_assignments)}
  end

  @impl true
  def handle_params(_params, _url, socket) do
    {:noreply, socket}
  end

  defp assignment_source(device, agent_token_id) do
    cond do
      # Direct assignment
      Enum.any?(device.agent_assignments || [], fn a ->
        a.agent_token_id == agent_token_id and a.enabled
      end) ->
        {:direct, "Directly assigned"}

      # Site assignment
      device.site && device.site.agent_token_id == agent_token_id ->
        {:site, "From site: #{device.site.name}"}

      # Organization assignment
      device.organization && device.organization.default_agent_token_id == agent_token_id ->
        {:organization, "From organization"}

      # Shouldn't happen but handle gracefully
      true ->
        {:unknown, "Unknown"}
    end
  end

  defp source_badge_class(source) do
    case source do
      :direct -> "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300"
      :site -> "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300"
      :organization -> "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-300"
      :unknown -> "bg-zinc-100 text-zinc-800 dark:bg-zinc-800 dark:text-zinc-300"
    end
  end
end
