import { useCallback } from "react";
import { goodDatabaseToStoredArtifacts, type GoodImportDatabase, storedArtifactsToGood } from "../../../lib/goodInterop";
import type { ArtifactRepositoryPort, ScanExportPort } from "../../../infrastructure/repositories/rendererBridgeRepositoryTypes";
import type { StoredArtifactRecord } from "../../../types/storage";

interface UseScanGoodInteropInput {
  artifactRepo?: ArtifactRepositoryPort;
  exportRepo?: ScanExportPort;
  onStoredArtifactsChanged?: () => Promise<void>;
  setStoredTotal: (value: number | null) => void;
  bridgeReady: boolean;
}

export function useScanGoodInterop({
  artifactRepo,
  exportRepo,
  onStoredArtifactsChanged,
  setStoredTotal,
  bridgeReady,
}: UseScanGoodInteropInput) {
  const canGoodInterop = bridgeReady && Boolean(artifactRepo?.loadAll) && Boolean(artifactRepo?.saveMany);

  const exportGoodFromStore = useCallback(async () => {
    if (!artifactRepo?.loadAll || !exportRepo?.exportGood) return { ok: false, count: 0 };
    const loaded = await artifactRepo.loadAll();
    const records = loaded.artifacts ?? [];
    const good = storedArtifactsToGood(records);
    const result = await exportRepo.exportGood(good);
    return { ok: Boolean(result.ok), path: result.path, count: good.artifacts.length };
  }, [artifactRepo, exportRepo]);

  const importGoodArtifacts = useCallback(async (records: StoredArtifactRecord[]) => {
    if (!artifactRepo?.saveMany || records.length === 0) return { ok: false, added: 0, updated: 0 };
    const result = await artifactRepo.saveMany(records);
    if (typeof result.total === "number") setStoredTotal(result.total);
    await onStoredArtifactsChanged?.();
    return { ok: Boolean(result.ok), added: result.added ?? 0, updated: result.updated ?? 0 };
  }, [artifactRepo, onStoredArtifactsChanged, setStoredTotal]);

  const importGoodFromFile = useCallback(async () => {
    if (!exportRepo?.importGoodFile || !artifactRepo?.saveMany) {
      return { ok: false, added: 0, updated: 0, count: 0, error: "GOOD import is unavailable." };
    }
    const fileResult = await exportRepo.importGoodFile();
    if (fileResult.canceled) return { ok: false, added: 0, updated: 0, count: 0, canceled: true };
    if (!fileResult.ok) {
      return { ok: false, added: 0, updated: 0, count: 0, path: fileResult.path, error: fileResult.error };
    }
    const records = goodDatabaseToStoredArtifacts(fileResult.database as GoodImportDatabase);
    if (records.length === 0) {
      return { ok: false, added: 0, updated: 0, count: 0, path: fileResult.path, error: "No valid GOOD artifacts found." };
    }
    const saved = await importGoodArtifacts(records);
    return { ...saved, count: records.length, path: fileResult.path };
  }, [artifactRepo, exportRepo, importGoodArtifacts]);

  return {
    canGoodInterop,
    exportGoodFromStore,
    importGoodFromFile,
    importGoodArtifacts,
  };
}
