type ChatAuthorRecord = {
  id: string;
  name?: string | null;
  avatar_url?: string | null;
};

export type MessageAuthorDisplay = {
  name: string;
  avatarUrl: string | null;
  initial: string;
};

type GetMessageAuthorDisplayParams = {
  userId: string;
  members: Record<string, ChatAuthorRecord | undefined>;
  currentUser: ChatAuthorRecord | null;
  failedAvatarUserIds: Record<string, boolean>;
};

function firstNonEmpty(value?: string | null) {
  const trimmed = value?.trim();
  return trimmed ? trimmed : null;
}

export function getMessageAuthorDisplay({
  userId,
  members,
  currentUser,
  failedAvatarUserIds,
}: GetMessageAuthorDisplayParams): MessageAuthorDisplay {
  const member = members[userId];
  const currentUserMatch = currentUser?.id === userId ? currentUser : null;

  const name =
    firstNonEmpty(member?.name) ??
    firstNonEmpty(currentUserMatch?.name) ??
    "Utilisateur";

  const avatarUrl = failedAvatarUserIds[userId]
    ? null
    : firstNonEmpty(member?.avatar_url) ?? firstNonEmpty(currentUserMatch?.avatar_url);

  return {
    name,
    avatarUrl,
    initial: name.charAt(0).toUpperCase() || "U",
  };
}
