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

  alias Towerops.Gaiia.Reconciliation

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

    {:ok,
     socket
     |> assign(:organization, org)
     |> assign(:page_title, "Gaiia Inventory Reconciliation")}
  end

  @impl true
  def handle_params(params, _url, socket) do
    tab = Map.get(params, "tab", "summary")

    {:noreply,
     socket
     |> assign(:active_tab, tab)
     |> load_reconciliation()}
  end

  @impl true
  def handle_event("select_tab", %{"tab" => tab}, socket) do
    org = socket.assigns.organization

    {:noreply,
     push_patch(socket,
       to: ~p"/orgs/#{org.slug}/settings/integrations/gaiia/reconciliation?tab=#{tab}"
     )}
  end

  defp load_reconciliation(socket) do
    report = Reconciliation.reconcile(socket.assigns.organization.id)
    assign(socket, :report, report)
  end
end
