defmodule ToweropsWeb.GraphQL.Resolvers.Agent do @moduledoc "GraphQL resolvers for agent queries and mutations." alias Towerops.Agents def list(_parent, _args, %{context: %{organization_id: org_id}}) do agents = Agents.list_organization_agent_tokens(org_id) {:ok, agents} end def list(_parent, _args, _resolution), do: {:error, "Authentication required"} def get(_parent, %{id: id}, %{context: %{organization_id: org_id}}) do agent = Agents.get_agent_token!(id) if agent.organization_id == org_id do {:ok, agent} else {:error, "Agent not found"} end rescue Ecto.NoResultsError -> {:error, "Agent not found"} end def get(_parent, _args, _resolution), do: {:error, "Authentication required"} def create(_parent, %{name: name}, %{context: %{organization_id: org_id}}) do case Agents.create_agent_token(org_id, name) do {:ok, agent_token, raw_token} -> {:ok, %{ id: agent_token.id, name: agent_token.name, enabled: agent_token.enabled, token: raw_token, inserted_at: agent_token.inserted_at }} {:error, changeset} -> {:error, format_errors(changeset)} end end def create(_parent, _args, _resolution), do: {:error, "Authentication required"} def delete(_parent, %{id: id}, %{context: %{organization_id: org_id}}) do agent = Agents.get_agent_token!(id) if agent.organization_id == org_id do case Agents.delete_agent_token(id) do {:ok, _} -> {:ok, %{success: true, message: "Agent deleted"}} {:error, _} -> {:ok, %{success: false, message: "Could not delete agent"}} end else {:error, "Agent not found"} end rescue Ecto.NoResultsError -> {:error, "Agent not found"} end def delete(_parent, _args, _resolution), do: {:error, "Authentication required"} defp format_errors(changeset) do changeset |> Ecto.Changeset.traverse_errors(fn {msg, opts} -> Regex.replace(~r"%{(\w+)}", msg, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) |> Enum.map_join("; ", fn {field, messages} -> "#{field}: #{Enum.join(messages, ", ")}" end) end end