import type {
  DirectMessageContact,
  DirectMessagePersonLike,
} from '@/services/direct_messages.types';

export function displayName(user: DirectMessagePersonLike | null): string {
  if (!user) return '—';
  const full = [user.firstName, user.lastName].filter(Boolean).join(' ').trim();
  return full || user.email || '—';
}

export function conversationKey(userId: string, studentId: string | null): string {
  return `${userId}:${studentId ?? 'none'}`;
}

export function studentWhere(studentId: string | null) {
  return studentId ? { studentId } : { studentId: null };
}

/** Removes duplicate contacts (a staff member can connect via several students). */
export function dedupeContacts(
  rows: readonly DirectMessageContact[],
): DirectMessageContact[] {
  const seen = new Set<string>();
  const result: DirectMessageContact[] = [];
  for (const row of rows) {
    if (seen.has(row.conversationKey)) continue;
    seen.add(row.conversationKey);
    result.push(row);
  }
  return result;
}
