// Import from node_modules using relative path

import {
  App as CapacitorApp,
  AppLaunchUrl,
  BackButtonListener,
} from "../../../node_modules/@capacitor/app";
import type { PluginListenerHandle } from "@capacitor/core";

/**
 * Interface defining the app event listener functionality
 * Supports 'backButton' and 'appUrlOpen' events from Capacitor
 */
interface AppInterface {
  /**
   * Add listener for back button events
   * @param eventName - Must be 'backButton'
   * @param listenerFunc - Callback function for back button events
   * @returns Promise that resolves with a removable listener handle
   */
  addListener(
    eventName: "backButton",
    listenerFunc: BackButtonListener,
  ): Promise<PluginListenerHandle> & PluginListenerHandle;

  /**
   * Add listener for app URL open events
   * @param eventName - Must be 'appUrlOpen'
   * @param listenerFunc - Callback function for URL open events
   * @returns Promise that resolves with a removable listener handle
   */
  addListener(
    eventName: "appUrlOpen",
    listenerFunc: (data: AppLaunchUrl) => void,
  ): Promise<PluginListenerHandle> & PluginListenerHandle;
}

/**
 * App wrapper for Capacitor functionality
 * Provides type-safe event listeners for back button and URL open events
 */
export const App: AppInterface = {
  addListener(
    eventName: "backButton" | "appUrlOpen",
    listenerFunc: BackButtonListener | ((data: AppLaunchUrl) => void),
  ): Promise<PluginListenerHandle> & PluginListenerHandle {
    if (eventName === "backButton") {
      return CapacitorApp.addListener(
        eventName,
        listenerFunc as BackButtonListener,
      ) as Promise<PluginListenerHandle> & PluginListenerHandle;
    } else {
      return CapacitorApp.addListener(
        eventName,
        listenerFunc as (data: AppLaunchUrl) => void,
      ) as Promise<PluginListenerHandle> & PluginListenerHandle;
    }
  },
};
