import AsyncStorage from '@react-native-async-storage/async-storage';
import { ps } from '@/api/client';

/**
 * UnifiedPush integration (distributor: ntfy).
 *
 * IMPORTANT ARCHITECTURE NOTE
 * ---------------------------
 * The ParkSmarter backend only delivers push via FCM, keyed on the device token
 * registered through `PUT /api/Device`. A UnifiedPush endpoint (an ntfy URL)
 * cannot receive FCM directly, so server-initiated push requires a BRIDGE:
 *
 *   ParkSmarter server --FCM--> [bridge holding an FCM token] --HTTP--> ntfy topic
 *                                                                         |
 *                                                        UnifiedPush distributor (ntfy app)
 *                                                                         v
 *                                                                    this app
 *
 * Until that bridge exists, session-expiry reminders are handled entirely by
 * on-device local notifications (see localReminders.ts), which covers the main
 * use case without any server push. This module wires the UnifiedPush side so
 * the app is ready to be a push target once the bridge (or a self-hosted relay
 * that we register with `PUT /api/Device`) is in place.
 *
 * The `react-native-unifiedpush-connector` API surface varies by version; treat the
 * calls below as the integration point to confirm against the installed version.
 * It's lazy-required so the app runs fine even before push is fully wired.
 */

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;
  }
}

/** Kick off distributor discovery + registration (call after login). */
export async function registerUnifiedPush(): Promise<void> {
  const UnifiedPush = loadUnifiedPush();
  if (!UnifiedPush) return;
  const distributors: string[] = await UnifiedPush.getDistributors();
  if (!distributors.length) {
    // No UnifiedPush distributor installed (e.g. ntfy). Local reminders still work.
    return;
  }
  const saved = await UnifiedPush.getSavedDistributor?.();
  const distributor = saved ?? distributors[0];
  await UnifiedPush.saveDistributor(distributor);
  await UnifiedPush.registerDevice(INSTANCE);
}

/**
 * Handle the endpoint the distributor hands back (wire this to the library's
 * `onNewEndpoint` event in the app root). We persist it and, once a bridge is
 * available, register it with the backend so the server can reach us.
 */
export async function onNewEndpoint(endpoint: string): Promise<void> {
  await AsyncStorage.setItem(ENDPOINT_KEY, endpoint);
  // When the FCM->ntfy bridge is live, register the bridge-issued token here:
  // await ps.updateDeviceToken({ pushNotificationsToken: bridgeToken, deviceType: '1' });
  void ps; // referenced so the intended integration is explicit
}

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