import type { ProfileDirectoryItem } from "./profileDirectoryRecord";

/**
 * The name a directory tile shows.
 *
 * An individual is identified by `display_name` (real name only when they chose
 * to show it, BE-169), else the nickname — never first/last name.
 *
 * An organization or volunteer team is identified by its registered name
 * (PDF p.9). The directory resource sends it as `display_name` / `company_name`
 * (backend `3f55f35f`, BE-294); `nickname` is only the username the account was
 * seeded with, so it is the fallback for an older payload that has neither.
 */
export function directoryDisplayName(
  profile: ProfileDirectoryItem | null | undefined,
  isIndividual: boolean,
): string {
  if (!profile) return "—";
  const clean = (value: string | null | undefined) => value?.trim() || "";

  if (isIndividual) {
    return clean(profile.display_name) || clean(profile.nickname) || "—";
  }

  const details = profile.user_details;
  const fullName =
    details && "first_name" in details
      ? [details.first_name, details.last_name].filter(Boolean).join(" ").trim()
      : "";
  const companyName = "company_name" in profile ? clean(profile.company_name) : "";

  return (
    clean(profile.display_name) ||
    companyName ||
    clean(profile.nickname) ||
    fullName ||
    "—"
  );
}
