export interface MonitoringLogEntry {
  id: number;
  timestamp: string | null;
  level: 'ERROR' | 'WARN' | 'INFO' | 'DEBUG' | null;
  message: string;
  context: Record<string, unknown>;
  client_uuid?: string;
}

export interface MonitoringClient {
  uuid: string;
  hostname?: string | null;
  description?: string | null;
  ip?: string | null;
  model?: string | null;
  groupId?: number | null;
  groupName?: string | null;
  registrationTime?: string | null;
  lastAlive?: string | null;
  isAlive: boolean;
  status: 'healthy' | 'warning' | 'critical' | 'offline';
  currentEventId?: number | null;
  currentProcess?: string | null;
  processStatus?: string | null;
  processPid?: number | null;
  screenHealthStatus?: string | null;
  lastScreenshotAnalyzed?: string | null;
  lastScreenshotHash?: string | null;
  latestScreenshotType?: 'periodic' | 'event_start' | 'event_stop' | null;
  priorityScreenshotType?: 'event_start' | 'event_stop' | null;
  priorityScreenshotReceivedAt?: string | null;
  hasActivePriorityScreenshot?: boolean;
  screenshotUrl: string;
  logCounts24h: {
    error: number;
    warn: number;
    info: number;
    debug: number;
  };
  latestLog?: MonitoringLogEntry | null;
  latestError?: MonitoringLogEntry | null;
}

export interface MonitoringOverview {
  summary: {
    totalClients: number;
    onlineClients: number;
    offlineClients: number;
    healthyClients: number;
    warningClients: number;
    criticalClients: number;
    errorLogs: number;
    warnLogs: number;
    activePriorityScreenshots: number;
  };
  periodHours: number;
  gracePeriodSeconds: number;
  since: string;
  timestamp: string;
  clients: MonitoringClient[];
}

export interface ClientLogsResponse {
  client_uuid: string;
  logs: MonitoringLogEntry[];
  count: number;
  limit: number;
}

async function parseJsonResponse<T>(response: Response, fallbackMessage: string): Promise<T> {
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.error || fallbackMessage);
  }
  return data as T;
}

export async function fetchMonitoringOverview(hours = 24): Promise<MonitoringOverview> {
  const response = await fetch(`/api/client-logs/monitoring-overview?hours=${hours}`, {
    credentials: 'include',
  });
  return parseJsonResponse<MonitoringOverview>(response, 'Fehler beim Laden der Monitoring-Übersicht');
}

export async function fetchRecentClientErrors(limit = 20): Promise<MonitoringLogEntry[]> {
  const response = await fetch(`/api/client-logs/recent-errors?limit=${limit}`, {
    credentials: 'include',
  });
  const data = await parseJsonResponse<{ errors: MonitoringLogEntry[] }>(
    response,
    'Fehler beim Laden der letzten Fehler'
  );
  return data.errors;
}

export async function fetchClientMonitoringLogs(
  uuid: string,
  options: { level?: string; limit?: number } = {}
): Promise<MonitoringLogEntry[]> {
  const params = new URLSearchParams();
  if (options.level && options.level !== 'ALL') {
    params.set('level', options.level);
  }
  params.set('limit', String(options.limit ?? 100));

  const response = await fetch(`/api/client-logs/${uuid}/logs?${params.toString()}`, {
    credentials: 'include',
  });
  const data = await parseJsonResponse<ClientLogsResponse>(response, 'Fehler beim Laden der Client-Logs');
  return data.logs;
}