import { useEffect } from "react";
import type { Dispatch, SetStateAction } from "react";
import type { CaptureResult } from "../../../types/global";
import type { ArtifactRepositoryPort } from "../../../infrastructure/repositories/rendererBridgeRepositoryTypes";
import { clampScanLimit } from "../../../lib/scannerSession";

interface ScanViewStateSyncInput {
  artifactRepo?: ArtifactRepositoryPort;
  latestCapture: CaptureResult | null;
  scanLimitTouched: boolean;
  setScanLimit: Dispatch<SetStateAction<number>>;
  setStoredTotal: Dispatch<SetStateAction<number | null>>;
}

export function useScanViewStateSync({
  artifactRepo,
  latestCapture,
  scanLimitTouched,
  setScanLimit,
  setStoredTotal,
}: ScanViewStateSyncInput) {
  useEffect(() => {
    const detectedCount = latestCapture?.inventoryCount?.current ?? 0;
    if (!scanLimitTouched && detectedCount > 0) {
      setScanLimit(clampScanLimit(detectedCount));
    }
  }, [latestCapture?.inventoryCount?.current, scanLimitTouched, setScanLimit]);

  useEffect(() => {
    artifactRepo?.loadAll().then((result) => {
      if (result?.ok) setStoredTotal(result.total);
    }).catch(() => undefined);
  }, [artifactRepo, setStoredTotal]);
}

