import { Capacitor } from "@capacitor/core";
import { QRScannerService } from "./types";
import { CapacitorQRScanner } from "./CapacitorQRScanner";
import { WebInlineQRScanner } from "./WebInlineQRScanner";
import { logger } from "@/utils/logger";

/**
 * Factory class for creating QR scanner instances based on platform
 */
export class QRScannerFactory {
  private static instance: QRScannerService | null = null;

  private static isNativePlatform(): boolean {
    // Debug logging for build flags
    logger.log("Build flags:", {
      IS_MOBILE:
        typeof __IS_MOBILE__ !== "undefined" ? __IS_MOBILE__ : "undefined",
      USE_QR_READER:
        typeof __USE_QR_READER__ !== "undefined"
          ? __USE_QR_READER__
          : "undefined",
      VITE_PLATFORM: process.env.VITE_PLATFORM,
    });

    const capacitorNative = Capacitor.isNativePlatform();
    const isMobile =
      typeof __IS_MOBILE__ !== "undefined" ? __IS_MOBILE__ : capacitorNative;
    const platform = Capacitor.getPlatform();

    logger.log("Platform detection:", {
      capacitorNative,
      isMobile,
      platform,
      userAgent: navigator.userAgent,
    });

    // Always use native scanner on Android/iOS
    if (platform === "android" || platform === "ios") {
      logger.log("Using native scanner due to platform:", platform);
      return true;
    }

    // For other platforms, use native if available
    const useNative = capacitorNative || isMobile;
    logger.log("Platform decision:", {
      useNative,
      reason: useNative ? "capacitorNative/isMobile" : "web",
    });
    return useNative;
  }

  /**
   * Get a QR scanner instance appropriate for the current platform
   */
  static getInstance(): QRScannerService {
    if (!this.instance) {
      const isNative = this.isNativePlatform();
      logger.log(
        `Creating QR scanner for platform: ${isNative ? "native" : "web"}`,
      );

      try {
        if (isNative) {
          logger.log("Using native MLKit scanner");
          this.instance = new CapacitorQRScanner();
        } else if (
          typeof __USE_QR_READER__ !== "undefined"
            ? __USE_QR_READER__
            : !isNative
        ) {
          logger.log("Using web QR scanner");
          this.instance = new WebInlineQRScanner();
        } else {
          throw new Error(
            "No QR scanner implementation available for this platform",
          );
        }
      } catch (error) {
        logger.error("Error creating QR scanner:", error);
        throw error;
      }
    }
    return this.instance!;
  }

  /**
   * Clean up the current scanner instance
   */
  static async cleanup(): Promise<void> {
    if (this.instance) {
      try {
        await this.instance.cleanup();
      } catch (error) {
        logger.error("Error cleaning up QR scanner:", error);
      } finally {
        this.instance = null;
      }
    }
  }
}
