import { apiGet, apiPost } from './client';

export interface SyncStats {
  syncStats: {
    total_syncs: string;
    successful_syncs: string;
    failed_syncs: string;
    total_messages: string;
    total_contacts: string;
    last_sync_at: string | null;
  };
  entityCounts: {
    messages: number;
    contacts: number;
    conversations: number;
    albums: number;
    photos: number;
    calendars: number;
    events: number;
    pending_sends: number;
  };
}

export interface SyncHistoryRecord {
  id: string;
  device_id: string;
  module: string;
  started_at: string;
  completed_at: string | null;
  status: 'pending' | 'success' | 'error';
  messages_synced: number;
  contacts_synced: number;
  conversations_synced: number;
  error_message: string | null;
  created_at: string;
}

export type SyncSourceStatus = 'healthy' | 'stale' | 'failing';

export interface SyncHealthEntry {
  source: string;
  lastSuccessAt: string | null;
  lastAttemptAt: string | null;
  lastError: string | null;
  status: SyncSourceStatus;
}

export interface SendQueueSummary {
  queued: number;
  failed: number;
  sentLastHour: number;
  oldestQueuedAt: string | null;
}

export interface SyncThroughput {
  imessages: number;
  mail: number;
  contacts: number;
  photos: number;
  events: number;
  totals: {
    imessages: number;
    mail: number;
    contacts: number;
    photos: number;
    events: number;
  };
}

export interface FailedSendItem {
  id: string;
  deviceId: string;
  toHandle: string;
  body: string;
  status: string;
  failureReason: string | null;
  createdAt: string;
  updatedAt: string;
}

export async function fetchSyncStats(deviceId: string): Promise<SyncStats> {
  try {
    return await apiGet<SyncStats>(`/client/sync/stats?device_id=${encodeURIComponent(deviceId)}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchSyncStats failed');
  }
}

export async function fetchSyncHistory(deviceId: string, limit = 20): Promise<SyncHistoryRecord[]> {
  try {
    const params = new URLSearchParams({ device_id: deviceId, limit: String(limit) });
    const result = await apiGet<{ history: SyncHistoryRecord[] }>(`/client/sync/history?${params}`);
    return result.history;
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchSyncHistory failed');
  }
}

export async function fetchSyncHealth(): Promise<SyncHealthEntry[]> {
  try {
    return await apiGet<SyncHealthEntry[]>('/client/sync/health');
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchSyncHealth failed');
  }
}

export async function fetchSendQueueSummary(): Promise<SendQueueSummary> {
  try {
    return await apiGet<SendQueueSummary>('/client/sync/send-queue/summary');
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchSendQueueSummary failed');
  }
}

export async function fetchSyncThroughput(window = '24h'): Promise<SyncThroughput> {
  try {
    return await apiGet<SyncThroughput>(`/client/sync/throughput?window=${encodeURIComponent(window)}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchSyncThroughput failed');
  }
}

export async function fetchFailedSends(): Promise<FailedSendItem[]> {
  try {
    return await apiGet<FailedSendItem[]>('/client/sync/send-queue/failed');
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchFailedSends failed');
  }
}

export async function retrySend(id: string): Promise<FailedSendItem> {
  try {
    return await apiPost<FailedSendItem>(`/client/sync/send-queue/${encodeURIComponent(id)}/retry`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('retrySend failed');
  }
}
