/**
 * Honorific name prefix (title) for a user — e.g. `Dr.`, `Ms.` Stored on
 * `users.name_prefix` as an enum so the UI can render "Dr. Williams" even when
 * the person did not type the title into their name. Display labels include the
 * trailing period; the stored value is the lowercase key.
 */
export const USER_NAME_PREFIXES = Object.freeze({
  MR: 'mr',
  MRS: 'mrs',
  MS: 'ms',
  MX: 'mx',
  DR: 'dr',
  PROF: 'prof',
});

export type UserNamePrefix =
  (typeof USER_NAME_PREFIXES)[keyof typeof USER_NAME_PREFIXES];

export const USER_NAME_PREFIX_VALUES: readonly UserNamePrefix[] = Object.freeze(
  Object.values(USER_NAME_PREFIXES),
);

/** Stored value → human label (with trailing period). */
export const USER_NAME_PREFIX_LABELS: Record<UserNamePrefix, string> =
  Object.freeze({
    mr: 'Mr.',
    mrs: 'Mrs.',
    ms: 'Ms.',
    mx: 'Mx.',
    dr: 'Dr.',
    prof: 'Prof.',
  });

/** "Dr. Sarah Williams" from a prefix + names; omits missing parts. */
export function formatPersonName(
  namePrefix: string | null | undefined,
  firstName: string | null | undefined,
  lastName: string | null | undefined,
): string {
  const label =
    namePrefix && namePrefix in USER_NAME_PREFIX_LABELS
      ? USER_NAME_PREFIX_LABELS[namePrefix as UserNamePrefix]
      : null;
  return [label, firstName, lastName]
    .filter((part): part is string => typeof part === 'string' && part.length > 0)
    .join(' ')
    .trim();
}
