import { api } from './api';
import type { MonitoredService, PingResult, PingHistoryEntry, StatusSummary, SystemHealth, UserOverview, BroadcastPayload, BroadcastPreviewPayload } from '../types/admin.types';

interface ApiResponse<T> {
  success: boolean;
  data: T;
}

export interface FdiskSyncLogEntry {
  ts: string;
  line: string;
}

export interface FdiskSyncLogsResponse {
  running: boolean;
  logs: FdiskSyncLogEntry[];
}

export const adminApi = {
  getServices: () => api.get<ApiResponse<MonitoredService[]>>('/api/admin/services').then(r => r.data.data),
  createService: (data: { name: string; url: string }) => api.post<ApiResponse<MonitoredService>>('/api/admin/services', data).then(r => r.data.data),
  updateService: (id: string, data: Partial<MonitoredService>) => api.put<ApiResponse<MonitoredService>>(`/api/admin/services/${id}`, data).then(r => r.data.data),
  deleteService: (id: string) => api.delete(`/api/admin/services/${id}`).then(() => undefined),
  pingAll: () => api.get<ApiResponse<PingResult[]>>('/api/admin/services/ping').then(r => r.data.data),
  getStatusSummary: () => api.get<ApiResponse<StatusSummary>>('/api/admin/services/status-summary').then(r => r.data.data),
  getSystemHealth: () => api.get<ApiResponse<SystemHealth>>('/api/admin/system/health').then(r => r.data.data),
  getUsers: () => api.get<ApiResponse<UserOverview[]>>('/api/admin/users').then(r => r.data.data),
  broadcast: (data: BroadcastPayload) => api.post<ApiResponse<{ sent: number }>>('/api/admin/notifications/broadcast', data).then(r => r.data.data),
  broadcastPreview: (data: BroadcastPreviewPayload) => api.post<ApiResponse<{ count: number }>>('/api/admin/notifications/broadcast/preview', data).then(r => r.data.data),
  getPingHistory: (serviceId: string) => api.get<ApiResponse<PingHistoryEntry[]>>(`/api/admin/services/${serviceId}/ping-history`).then(r => r.data.data),
  fdiskSyncLogs: () => api.get<ApiResponse<FdiskSyncLogsResponse>>('/api/admin/fdisk-sync/logs').then(r => r.data.data),
  fdiskSyncTrigger: (force = false) => api.post<ApiResponse<{ started: boolean }>>('/api/admin/fdisk-sync/trigger', { force }).then(r => r.data.data),
  purgeFdiskData: (userId: string) => api.delete<ApiResponse<{ profileFieldsCleared: number; ausbildungen: number; befoerderungen: number; untersuchungen: number; fahrgenehmigungen: number }>>(`/api/admin/users/${userId}/fdisk-data`).then(r => r.data.data),
  purgeUserData: (userId: string) => api.post<ApiResponse<Record<string, number>>>(`/api/admin/users/${userId}/purge-data`).then(r => r.data.data),
};
