defmodule MvWeb.RoleLive.Helpers do
  @moduledoc """
  Shared helper functions for RoleLive modules.
  """
  use Gettext, backend: MvWeb.Gettext

  @doc """
  Formats an error for display to the user.
  Extracts error messages from Ash.Error.Invalid and joins them.
  """
  @spec format_error(Ash.Error.Invalid.t() | String.t() | any()) :: String.t()
  def format_error(%Ash.Error.Invalid{} = error) do
    Enum.map_join(error.errors, ", ", fn e -> e.message end)
  end

  def format_error(error) when is_binary(error), do: error
  def format_error(_error), do: gettext("An error occurred")

  @doc """
  Returns the CSS badge class for a permission set name.
  """
  @spec permission_set_badge_class(String.t()) :: String.t()
  def permission_set_badge_class("own_data"), do: "badge badge-neutral badge-sm"
  def permission_set_badge_class("read_only"), do: "badge badge-info badge-sm"
  def permission_set_badge_class("normal_user"), do: "badge badge-success badge-sm"
  def permission_set_badge_class("admin"), do: "badge badge-error badge-sm"
  def permission_set_badge_class(_), do: "badge badge-ghost badge-sm"

  @doc """
  Builds Ash options with actor and domain, ensuring actor is never nil in real paths.
  """
  @spec opts_with_actor(keyword(), map() | nil, atom()) :: keyword()
  def opts_with_actor(base_opts \\ [], actor, domain) do
    opts = Keyword.put(base_opts, :domain, domain)

    if actor do
      Keyword.put(opts, :actor, actor)
    else
      require Logger
      Logger.warning("opts_with_actor called with nil actor - this may bypass policies")
      opts
    end
  end
end
