import { useEffect } from "react";
import type { AutomationRepositoryPort } from "../../../infrastructure/repositories/rendererBridgeRepositoryTypes";
import type { ScannerCommand } from "../../../types/global";
import type { VisibleGridScanOptions } from "./scanViewScanActions";

interface ScanCommandListenerInput {
  automationRepo?: AutomationRepositoryPort;
  autoScanRunning: boolean;
  isScanning: boolean;
  selectedSourceId: string;
  requestScanStop: (reason: string) => void;
  runGuidedAutoScan: (options?: { scanLimit?: number }) => Promise<void>;
  runVisibleGridScan: (options?: VisibleGridScanOptions) => Promise<void>;
}

export function useScanCommandListener({
  automationRepo,
  autoScanRunning,
  isScanning,
  selectedSourceId,
  requestScanStop,
  runGuidedAutoScan,
  runVisibleGridScan,
}: ScanCommandListenerInput) {
  useEffect(() => {
    if (!automationRepo?.onCommand) return;
    return automationRepo.onCommand((command: ScannerCommand) => {
      if (command === "stop") {
        requestScanStop("Hotkey/Dev-Stop gedrueckt.");
        return;
      }
      const commandType = typeof command === "string" ? command : command.type;
      const canStartNativeScan = Boolean(automationRepo.nativeScannerStart);
      if (commandType === "start-auto" && !autoScanRunning && !isScanning && (selectedSourceId || canStartNativeScan)) {
        if (typeof command === "string" || !command.scanEntryMode) {
          void runGuidedAutoScan(typeof command === "string" ? undefined : { scanLimit: command.scanLimit });
          return;
        }
        void runVisibleGridScan({ scanLimit: command.scanLimit, scanEntryMode: command.scanEntryMode });
      }
    });
  }, [automationRepo, autoScanRunning, isScanning, selectedSourceId, requestScanStop, runGuidedAutoScan, runVisibleGridScan]);
}
