import { useEffect } from 'react';
import { generatePath, LoaderFunctionArgs, useFetcher } from 'react-router-dom';

import { getMalwareApiClient } from '@/api/api';
import { apiWrapper } from '@/utils/api';

const loader = async ({ params }: LoaderFunctionArgs) => {
  const scanId = params.scanId ?? '';
  const getMalwareClassesForScan = apiWrapper({
    fn: getMalwareApiClient().getMalwareClassesForScan,
  });

  const classes = await getMalwareClassesForScan({
    modelScanResultsReq: {
      scan_id: scanId,
      fields_filter: {
        compare_filter: null,
        contains_filter: { filter_in: {} },
        match_filter: { filter_in: {} },
        order_filter: { order_fields: [] },
      },
      window: {
        offset: 0,
        size: Number.MAX_SAFE_INTEGER,
      },
    },
  });

  if (!classes.ok) {
    throw classes.error;
  }

  return classes.value._class ?? [];
};

export function useGetMalwareClassesForScan({ scanId }: { scanId: string }) {
  const fetcher = useFetcher<string[]>();

  useEffect(() => {
    fetcher.load(
      generatePath(`/data-component/malware/classes/scan/:scanId`, {
        scanId: encodeURIComponent(scanId),
      }),
    );
  }, [scanId]);

  return {
    status: fetcher.state,
    classes: fetcher.data ?? [],
  };
}

export const module = {
  loader,
};
