type NameUser = {
  id?: string;
  firstName: string;
  lastName: string;
  avatarUrl?: string | null;
  lastActiveAt?: Date | string | null;
  phone?: string | null;
  email?: string | null;
  status?: string;
};

/**
 * Resolve the public-facing name for a worker.
 * Prefers displayName for privacy; falls back to legal first + last.
 */
export function resolveWorkerDisplayName(
  displayName: string | null | undefined,
  user: { firstName?: string | null; lastName?: string | null } | null | undefined
): string {
  const custom = displayName?.trim();
  if (custom) return custom;
  return `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim() || 'Worker';
}

/**
 * Map a worker's user fields for public responses so the site shows displayName
 * instead of legal first/last name.
 */
export function toPublicWorkerUser<T extends NameUser>(
  user: T,
  displayName?: string | null
): T & { displayName: string } {
  const resolved = resolveWorkerDisplayName(displayName, user);
  const parts = resolved.split(/\s+/).filter(Boolean);
  const firstName = parts[0] || resolved;
  const lastName = parts.slice(1).join(' ');

  return {
    ...user,
    firstName,
    lastName,
    displayName: resolved,
  };
}

export function withPublicWorkerUser<
  T extends { displayName?: string | null; user: NameUser },
>(worker: T): T {
  return {
    ...worker,
    user: toPublicWorkerUser(worker.user, worker.displayName),
  };
}
