import { User, User_Role } from "@/types/proto/api/v1/user_service_pb";

export const isSuperUser = (user: User | undefined) => {
  return user && (user.role === User_Role.ADMIN || user.role === User_Role.HOST);
};

/**
 * Formats an anonymous creator_id into a display-friendly label.
 * Handles patterns like:
 * - "anonymous_abc123" -> "Anonymous #abc123"
 * - "anonymous_abc123_VGVzdA" -> "Anonymous (Test)" - base64 encoded name
 * - Legacy: "anonymous_abc123_John" -> "Anonymous (John)" - plain text name
 */
export function formatAnonymousName(creatorId: string): string {
  if (!creatorId.startsWith("anonymous_")) {
    return creatorId; // Not an anonymous ID, return as-is
  }

  // Extract parts: anonymous_<sessionId>_<optionalEncodedName>
  const parts = creatorId.split("_");
  if (parts.length < 2) {
    return "Anonymous";
  }

  const sessionId = parts[1]; // The random ID part
  const encodedName = parts.slice(2).join("_"); // Everything after sessionId

  if (encodedName) {
    // Try to decode base64-encoded name (new format for Unicode support)
    try {
      // URL-safe base64 decode: replace - with +, _ with /
      const base64 = encodedName.replace(/-/g, '+').replace(/_/g, '/');
      // Pad if needed
      const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
      const decoded = atob(padded);
      // Convert from UTF-8 bytes to string
      const bytes = Uint8Array.from(decoded, c => c.charCodeAt(0));
      const displayName = new TextDecoder('utf-8').decode(bytes);
      if (displayName && displayName.trim()) {
        return `Anonymous (${displayName.trim()})`;
      }
    } catch {
      // Fallback: treat as plain text (legacy format)
      if (/^[a-zA-Z0-9_-]+$/.test(encodedName)) {
        return `Anonymous (${encodedName})`;
      }
    }
  }

  // Show last 4 chars of sessionId for identification
  const shortId = sessionId.length > 4 ? sessionId.slice(-4) : sessionId;
  return `Anonymous #${shortId}`;
}

