/**
 * @file Capacitor Main Entry Point
 * @author Matthew Raymer
 *
 * This file initializes the deep linking system for the TimeSafari app.
 * It sets up the connection between Capacitor's URL handling and our deep link processor.
 *
 * Deep Linking Flow:
 * 1. Capacitor receives URL open event
 * 2. Event is passed to DeepLinkHandler
 * 3. URL is validated and processed
 * 4. Router navigates to appropriate view
 *
 * Integration Points:
 * - Capacitor App plugin for URL handling
 * - Vue Router for navigation
 * - Error handling system
 * - Logging system
 *
 * Type Safety:
 * - Uses DeepLinkHandler for type-safe parameter processing
 * - Ensures type safety between Capacitor events and app routing
 * - Maintains type checking through the entire deep link flow
 *
 * @example
 * // URL open event from OS
 * timesafari://claim/123?view=details
 * // Processed and routed to appropriate view with type-safe parameters
 */

import { initializeApp } from "./main.common";
import { App } from "./libs/capacitor/app";
import router from "./router";
import { handleApiError } from "./services/api";
import { AxiosError } from "axios";
import { DeepLinkHandler } from "./services/deepLinks";
import { logger, safeStringify } from "./utils/logger";

logger.log("[Capacitor] Starting initialization");
logger.log("[Capacitor] Platform:", process.env.VITE_PLATFORM);

const app = initializeApp();

// Initialize API error handling for unhandled promise rejections
window.addEventListener("unhandledrejection", (event) => {
  if (event.reason?.response) {
    handleApiError(event.reason, event.reason.config?.url || "unknown");
  }
});

const deepLinkHandler = new DeepLinkHandler(router);

/**
 * Handles deep link routing for the application
 * Processes URLs in the format timesafari://<route>/<param>
 * Maps incoming deep links to corresponding router paths with parameters
 *
 * @param {Object} data - Deep link data object
 * @param {string} data.url - The full deep link URL to process
 * @returns {Promise<void>}
 *
 * @example
 * // Handles URLs like:
 * // timesafari://claim/01JMAAFZRNSRTQ0EBSD70A8E1H
 * // timesafari://project/abc123
 *
 * @throws {Error} If URL format is invalid
 */
const handleDeepLink = async (data: { url: string }) => {
  try {
    await router.isReady();
    await deepLinkHandler.handleDeepLink(data.url);
  } catch (error) {
    logger.error("[DeepLink] Error handling deep link: ", error);
    handleApiError(
      {
        message: error instanceof Error ? error.message : safeStringify(error),
      } as AxiosError,
      "deep-link",
    );
  }
};

// Register deep link handler with Capacitor
App.addListener("appUrlOpen", handleDeepLink);

logger.log("[Capacitor] Mounting app");
app.mount("#app");
logger.log("[Capacitor] App mounted");
