defmodule ToweropsWeb.OrgLive.Index do
  @moduledoc false
  use ToweropsWeb, :live_view

  alias Towerops.Accounts
  alias Towerops.Organizations

  @impl true
  def mount(_params, _session, socket) do
    user = socket.assigns.current_scope.user
    organizations = Organizations.list_user_organizations(user.id)

    {:ok,
     socket
     |> assign(:page_title, "Your Organizations")
     |> assign(:organizations, organizations)}
  end

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

  @impl true
  def handle_event("select_org", %{"org-id" => org_id}, socket) do
    user = socket.assigns.current_scope.user

    # Update user's default organization
    {:ok, _user} = Accounts.update_user_profile(user, %{default_organization_id: org_id})

    {:noreply, push_navigate(socket, to: ~p"/dashboard")}
  end
end
