/**
 * Types for the audit console — views audit events from mcpd.
 */

export interface AuditSession {
  sessionId: string;
  projectName: string;
  userName: string | null;
  firstSeen: string;
  lastSeen: string;
  eventCount: number;
  eventKinds: string[];
}

export interface AuditEvent {
  id: string;
  timestamp: string;
  sessionId: string;
  projectName: string;
  eventKind: string;
  source: string;
  verified: boolean;
  serverName: string | null;
  correlationId: string | null;
  parentEventId: string | null;
  userName?: string | null;
  tokenName?: string | null;
  tokenSha?: string | null;
  payload: Record<string, unknown>;
}

export interface AuditConsoleState {
  phase: 'loading' | 'ready' | 'error';
  error: string | null;

  // Sessions
  sessions: AuditSession[];
  selectedSessionIdx: number; // -1 = all sessions, 0+ = specific session
  showSidebar: boolean;

  // Events
  events: AuditEvent[];
  focusedEventIdx: number; // -1 = auto-scroll
  totalEvents: number;

  // Detail view
  detailEvent: AuditEvent | null;
  detailScrollOffset: number;

  // Filters
  projectFilter: string | null;
  kindFilter: string | null;
  dateFilter: 'all' | '1h' | '24h' | '7d' | 'today';
}

export type DateFilterPreset = 'all' | '1h' | '24h' | '7d' | 'today';

export const DATE_FILTER_CYCLE: DateFilterPreset[] = ['all', 'today', '1h', '24h', '7d'];

export const DATE_FILTER_LABELS: Record<DateFilterPreset, string> = {
  'all': 'all time',
  'today': 'today',
  '1h': 'last hour',
  '24h': 'last 24h',
  '7d': 'last 7 days',
};

export function dateFilterToFrom(preset: DateFilterPreset): string | undefined {
  if (preset === 'all') return undefined;
  const now = new Date();
  switch (preset) {
    case '1h': return new Date(now.getTime() - 60 * 60 * 1000).toISOString();
    case '24h': return new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
    case '7d': return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
    case 'today': {
      const start = new Date(now);
      start.setHours(0, 0, 0, 0);
      return start.toISOString();
    }
  }
}

export const EVENT_KIND_COLORS: Record<string, string> = {
  'pipeline_execution': 'blue',
  'stage_execution': 'cyan',
  'gate_decision': 'yellow',
  'prompt_delivery': 'magenta',
  'tool_call_trace': 'green',
  'rbac_decision': 'red',
  'session_bind': 'gray',
};

export const EVENT_KIND_LABELS: Record<string, string> = {
  'pipeline_execution': 'PIPELINE',
  'stage_execution': 'STAGE',
  'gate_decision': 'GATE',
  'prompt_delivery': 'PROMPT',
  'tool_call_trace': 'TOOL',
  'rbac_decision': 'RBAC',
  'session_bind': 'BIND',
};
