/**
 * Display formatters for the Sources feature. Kept as pure
 * functions / components so they're easy to test independently
 * of React.
 */

import { Badge } from '@/components/ui/badge';
import type { SourceStatus, SourceType } from './types';

const STATUS_LABEL: Record<SourceStatus, string> = {
  active: 'Active',
  suspended: 'Suspended',
};

const STATUS_VARIANT: Record<SourceStatus, 'success' | 'warning'> = {
  active: 'success',
  suspended: 'warning',
};

export function statusLabel(s: SourceStatus): string {
  return STATUS_LABEL[s] ?? s;
}

export function statusVariant(s: SourceStatus): 'success' | 'warning' {
  return STATUS_VARIANT[s] ?? 'warning';
}

export function StatusBadge({ status }: { status: SourceStatus }) {
  return <Badge variant={statusVariant(status)}>{statusLabel(status)}</Badge>;
}

const TYPE_LABEL: Record<SourceType, string> = {
  http: 'HTTP',
  mqtt: 'MQTT',
  ws: 'WebSocket',
  grpc: 'gRPC',
};

const TYPE_DESCRIPTION: Record<SourceType, string> = {
  http: 'Standard HTTP POST ingest with HMAC',
  mqtt: 'MQTT topic subscription',
  ws: 'WebSocket long-lived connection',
  grpc: 'gRPC bidi-streaming ingest (high-volume)',
};

export function typeLabel(t: SourceType): string {
  return TYPE_LABEL[t] ?? t;
}

export function typeDescription(t: SourceType): string {
  return TYPE_DESCRIPTION[t] ?? '';
}

export function TypeBadge({ type }: { type: SourceType }) {
  return <Badge variant="muted">{typeLabel(type)}</Badge>;
}

export function formatRateLimit(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M/s`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k/s`;
  return `${n}/s`;
}

export function formatDate(iso: string | null | undefined): string {
  if (!iso) return '\u2014';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleDateString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
}

/**
 * Render a JSONB value as a compact, syntax-highlighted block.
 * The Sources detail page uses this for allowed_targets and
 * match_expr (which are stored as JSONB and not edited in W2).
 */
export function JsonView({ value }: { value: unknown }) {
  if (value === null || value === undefined) {
    return <span className="text-xs text-muted-foreground">\u2014</span>;
  }
  let text: string;
  try {
    text = JSON.stringify(value, null, 2);
  } catch {
    text = String(value);
  }
  return (
    <pre className="max-h-48 overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-relaxed">
      <code>{text}</code>
    </pre>
  );
}
