import AsyncStorage from '@react-native-async-storage/async-storage';

/**
 * OPTIONAL UnifiedPush (ntfy) registration.
 *
 * Nothing time-based needs this: parking session-expiry reminders are scheduled
 * on-device (see localReminders.ts) with no server or push involved. This module
 * exists only for *future* genuinely server-initiated messages, delivered through
 * the user's own UnifiedPush distributor (e.g. ntfy) — self-hosted, no FCM, no
 * Google. It's a no-op unless a distributor is installed.
 *
 * The `react-native-unifiedpush-connector` API varies by version; lazy-required so
 * the app runs fine without it.
 */

const ENDPOINT_KEY = 'ps_unifiedpush_endpoint';
const INSTANCE = 'default';

function loadUnifiedPush(): any | null {
  try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    return require('react-native-unifiedpush-connector');
  } catch {
    return null;
  }
}

/** Register with the user's UnifiedPush distributor (ntfy), if one is installed. */
export async function registerUnifiedPush(): Promise<void> {
  const UnifiedPush = loadUnifiedPush();
  if (!UnifiedPush) return;
  const distributors: string[] = await UnifiedPush.getDistributors();
  if (!distributors.length) return; // no ntfy/distributor -> nothing to do
  const saved = await UnifiedPush.getSavedDistributor?.();
  await UnifiedPush.saveDistributor(saved ?? distributors[0]);
  await UnifiedPush.registerDevice(INSTANCE);
}

/** Persist the ntfy endpoint the distributor hands back. */
export async function onNewEndpoint(endpoint: string): Promise<void> {
  await AsyncStorage.setItem(ENDPOINT_KEY, endpoint);
}

export async function getSavedEndpoint(): Promise<string | null> {
  return AsyncStorage.getItem(ENDPOINT_KEY);
}
