type MessengerConnectionView = {
  id: string;
  type: 'TELEGRAM' | 'MAX';
  channelId: string;
  displayName?: string | null;
  username?: string | null;
  avatarAvailable?: boolean | null;
};

export function messengerConnectionName(connection: MessengerConnectionView | null | undefined) {
  const displayName = String(connection?.displayName || '').trim();
  if (displayName) {
    return displayName;
  }

  const username = String(connection?.username || '').trim();
  if (username) {
    return `@${username.replace(/^@+/, '')}`;
  }

  return connection?.channelId || 'Не подключен';
}

export function messengerConnectionHandle(connection: MessengerConnectionView | null | undefined) {
  const username = String(connection?.username || '').trim().replace(/^@+/, '');
  if (username) {
    return `@${username}`;
  }

  return connection?.channelId || '';
}

export function messengerConnectionInitials(connection: MessengerConnectionView | null | undefined, fallback: string) {
  const base = messengerConnectionName(connection);
  const initials = base
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part.charAt(0).toUpperCase())
    .join('');

  return initials || fallback;
}

export function messengerConnectionAvatarSrc(connection: MessengerConnectionView | null | undefined) {
  if (!connection?.avatarAvailable || connection.type !== 'TELEGRAM') {
    return '';
  }

  return `/api/messenger-avatar/${encodeURIComponent(connection.id)}`;
}
