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

  alias Towerops.Agents
  alias Towerops.Agents.AgentToken

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

    # Get agent token and verify it belongs to this organization
    agent_token = Towerops.Repo.get_by!(AgentToken, id: id, organization_id: organization.id)

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

    {:ok,
     socket
     |> assign(:page_title, "Edit #{agent_token.name}")
     |> 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, "Agent updated successfully")
         |> push_navigate(to: ~p"/orgs/#{socket.assigns.current_organization.slug}/agents/#{agent_token.id}")}

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