defmodule ToweropsWeb.AgentLive.Edit do
  @moduledoc false
  use ToweropsWeb, :live_view
  use Gettext, backend: ToweropsWeb.Gettext

  import ToweropsWeb.GettextHelpers

  alias Towerops.Agents
  alias Towerops.Agents.AgentToken

  @impl true
  def mount(%{"id" => id}, _session, socket) do
    organization = socket.assigns.current_scope.organization
    current_user = socket.assigns.current_scope.user

    # Superadmins can edit any agent; regular users only their org's agents
    agent_token =
      if current_user.is_superuser do
        Towerops.Repo.get!(AgentToken, id)
      else
        Towerops.Repo.get_by!(AgentToken, id: id, organization_id: organization.id)
      end

    changeset = AgentToken.update_changeset(agent_token, %{})

    {:ok,
     socket
     |> assign(:page_title, "Edit #{agent_token.name}")
     |> assign(:timezone, socket.assigns.current_scope.timezone)
     |> assign(:agent_token, agent_token)
     |> assign(:form, to_form(changeset))}
  end

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

  @impl true
  def handle_event("validate", %{"agent_token" => agent_params}, socket) do
    changeset =
      socket.assigns.agent_token
      |> AgentToken.update_changeset(agent_params)
      |> Map.put(:action, :validate)

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

  @impl true
  def handle_event("save", %{"agent_token" => agent_params}, socket) do
    case Agents.update_agent_token(socket.assigns.agent_token, agent_params) do
      {:ok, agent_token} ->
        {:noreply,
         socket
         |> put_flash(:info, t_equipment("Agent updated successfully"))
         |> push_navigate(to: ~p"/agents/#{agent_token.id}")}

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