defmodule MvWeb.Helpers.FieldTypeFormatter do
  @moduledoc """
  Helper functions for formatting field types for display.

  Handles both Ash type modules (e.g., `Ash.Type.String`) and simple atoms (e.g., `:string`).
  """

  alias MvWeb.Translations.FieldTypes

  @doc """
  Formats an Ash type for display.

  Handles both Ash type modules (e.g., `Ash.Type.String`) and simple atoms (e.g., `:string`).

  ## Parameters

    - `type` - An atom or module representing the field type

  ## Returns

    A human-readable string representation of the type

  ## Examples

      iex> format(:string)
      "String"

      iex> format(Ash.Type.String)
      "String"

      iex> format(Ash.Type.Date)
      "Date"
  """
  @spec format(atom() | module()) :: String.t()
  def format(type) when is_atom(type) do
    type_string = to_string(type)

    if String.contains?(type_string, "Ash.Type.") do
      type_string
      |> String.split(".")
      |> List.last()
      |> String.downcase()
      |> then(fn type_name ->
        try do
          type_atom = String.to_existing_atom(type_name)
          FieldTypes.label(type_atom)
        rescue
          ArgumentError -> FieldTypes.label(:string)
        end
      end)
    else
      FieldTypes.label(type)
    end
  end

  def format(type) do
    to_string(type)
  end
end
