defmodule MvWeb.ErrorHelpers do
  @moduledoc """
  Shared helpers for formatting errors in the web layer.

  Use `format_ash_error/1` for Ash errors so behaviour stays consistent
  (e.g. handling Invalid errors whose entries may lack a `:message` field).
  """

  @doc """
  Formats an Ash error for display to the user.

  Handles `Ash.Error.Invalid` by joining error messages; entries without
  a `:message` field are inspected to avoid FunctionClauseError.
  Other errors are inspected.
  """
  @spec format_ash_error(Ash.Error.t() | term()) :: String.t()
  def format_ash_error(%Ash.Error.Invalid{errors: errors}) when is_list(errors) do
    Enum.map_join(errors, ", ", fn
      %{message: message} when is_binary(message) -> message
      other -> inspect(other)
    end)
  end

  def format_ash_error(error), do: inspect(error)
end
