import { useEffect } from 'react';
import { AppState, type AppStateStatus } from 'react-native';
import { apiFetch } from '../lib/api';

const ping = (reason: string) => {
  apiFetch('/api/me/last-seen', { method: 'POST' })
    .then((r) => console.log('[presence] heartbeat OK (' + reason + ')', r))
    .catch((e) => console.warn('[presence] heartbeat FAIL (' + reason + '):', e?.message ?? e));
};

export function useLastSeenHeartbeat(enabled: boolean) {
  useEffect(() => {
    if (!enabled) return;

    // 60s-Interval während App im Foreground
    const interval = setInterval(() => {
      if (AppState.currentState === 'active') {
        ping('interval');
      }
    }, 60_000);

    // Phase-2-Alternative zur Edge-Function: bei App-Background sofort einen
    // finalen Ping → lastSeenAt ist exakt der Schließ-Zeitpunkt, kein 60s-Lag
    // mehr für den letzten-aktiv-Zustand. 90% Edge-Function-Gewinn ohne Setup.
    const sub = AppState.addEventListener('change', (next: AppStateStatus) => {
      if (next === 'background' || next === 'inactive') {
        ping('background');
      }
    });

    return () => {
      clearInterval(interval);
      sub.remove();
    };
  }, [enabled]);
}
