defmodule MvWeb.Helpers.MemberHelpers do
  @moduledoc """
  Helper functions for member-related operations in the web layer.

  Provides utilities for formatting and displaying member information.
  """

  alias Mv.Membership.Member

  @doc """
  Returns a display name for a member.

  Combines first_name and last_name if available, otherwise falls back to email.
  This ensures that members without names still have a meaningful display name.

  ## Examples

      iex> member = %Member{first_name: "John", last_name: "Doe", email: "john@example.com"}
      iex> MvWeb.Helpers.MemberHelpers.display_name(member)
      "John Doe"

      iex> member = %Member{first_name: nil, last_name: nil, email: "john@example.com"}
      iex> MvWeb.Helpers.MemberHelpers.display_name(member)
      "john@example.com"

      iex> member = %Member{first_name: "John", last_name: nil, email: "john@example.com"}
      iex> MvWeb.Helpers.MemberHelpers.display_name(member)
      "John"
  """
  def display_name(%Member{} = member) do
    name_parts =
      [member.first_name, member.last_name]
      |> Enum.reject(&blank?/1)
      |> Enum.map_join(" ", &String.trim/1)

    if name_parts == "" do
      member.email
    else
      name_parts
    end
  end

  @doc """
  Checks if a value is blank (nil, empty string, or only whitespace).

  ## Examples

      iex> MvWeb.Helpers.MemberHelpers.blank?(nil)
      true

      iex> MvWeb.Helpers.MemberHelpers.blank?("")
      true

      iex> MvWeb.Helpers.MemberHelpers.blank?("   ")
      true

      iex> MvWeb.Helpers.MemberHelpers.blank?("John")
      false
  """
  def blank?(nil), do: true
  def blank?(""), do: true
  def blank?(value) when is_binary(value), do: String.trim(value) == ""
  def blank?(_), do: false
end
