import NetInfo from '@react-native-community/netinfo';
import { syncChatsIncremental } from './data/chat.sync';

let listenerUnsubscribe: (() => void) | null = null;
let isSyncing = false;
let lastSyncTime = 0;
let wasOffline = true;

const SPEED_THRESHOLDS = {
  minDownloadMBps: 0.3,
  maxPingMs: 1000
};

export function startAutoSyncListener(token: string) {
  if (listenerUnsubscribe) return;

  listenerUnsubscribe = NetInfo.addEventListener(async (state) => {
    const online =
      state.isConnected === true &&
      (state.isInternetReachable === true || state.isInternetReachable === null);

    const justCameOnline = wasOffline && online === true;

    if (!online) {
      wasOffline = true;
      return;
    }

    if (justCameOnline) {
      wasOffline = false;
      await triggerSync(token);
      return;
    }

    const now = Date.now();
    if (now - lastSyncTime < 3 * 60 * 1000) {
      return;
    }
    console.log(lastSyncTime);

    wasOffline = false;
    await triggerSync(token);
  });
}

async function triggerSync(token: string) {
  if (isSyncing) return;
  isSyncing = true;

  try {
    await syncChatsIncremental(token);

    lastSyncTime = Date.now();
  } catch (e) {
    console.error('Auto-sync error:', e);
  } finally {
    isSyncing = false;
  }
}

export function stopAutoSyncListener() {
  if (listenerUnsubscribe) {
    listenerUnsubscribe();
    listenerUnsubscribe = null;
  }
}
