defmodule ToweropsWeb.Org.SettingsLive do
  @moduledoc false
  use ToweropsWeb, :live_view

  alias Towerops.Agents
  alias Towerops.Organizations

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

    # Get assignment breakdown to show impact
    assignment_breakdown = Agents.Stats.get_device_assignment_breakdown(organization.id)

    changeset = Organizations.change_organization(organization)

    {:ok,
     socket
     |> assign(:organization, organization)
     |> assign(:available_agents, available_agents)
     |> assign(:assignment_breakdown, assignment_breakdown)
     |> assign(:form, to_form(changeset))}
  end

  @impl true
  def handle_event("validate", %{"organization" => org_params}, socket) do
    changeset =
      socket.assigns.organization
      |> Organizations.change_organization(org_params)
      |> Map.put(:action, :validate)

    {:noreply, assign(socket, :form, to_form(changeset))}
  end

  @impl true
  def handle_event("save", %{"organization" => org_params}, socket) do
    case Organizations.update_organization(socket.assigns.organization, org_params) do
      {:ok, organization} ->
        {:noreply,
         socket
         |> put_flash(:info, "Organization settings updated successfully")
         |> push_navigate(to: ~p"/orgs/#{organization.slug}")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset))}
    end
  end

  @impl true
  def handle_event("apply_snmp_to_all", _params, socket) do
    {count, _} = Organizations.apply_snmp_config_to_all_equipment(socket.assigns.organization.id)

    {:noreply, put_flash(socket, :info, "Applied SNMP configuration to #{count} device records across all sites")}
  end

  @impl true
  def handle_event("apply_agent_to_all", _params, socket) do
    {count, _} = Organizations.apply_agent_to_all_equipment(socket.assigns.organization.id)

    {:noreply, put_flash(socket, :info, "Applied default agent to #{count} device records across all sites")}
  end
end
