import { usePointSelection } from "../../../stores/usePointSelection";
import { useQuery } from "@tanstack/react-query";
import { exportPoints, useDbTableName } from "../../../api";
import { handleExportSuccess } from "../ExportButton";
import { usePendingPointsFilters } from "../../../stores/usePendingPointsFilters";
import { STATUSES } from "../../../config.js";
import { appendFiltersInUse } from "../../../utils.js";

export const useExportPendingData = (enabled, onSettled) => {
  const { filters, ranges } = usePendingPointsFilters();
  const { categories, region } = filters;
  const { selection } = usePointSelection();
  const includedArr = [...selection.included];
  const excludedArr = [...selection.excluded];
  const dbTable = useDbTableName();

  return useQuery(
    ["export-initial", filters, selection],
    async () => {

      const getParams = () => {
        const params = new URLSearchParams({
          "status[]": [STATUSES.pending],
        });

        appendFiltersInUse(params, filters, ranges);
        params.append("status[]", [STATUSES.pending, STATUSES.cancelled].join(","));

        if (categories.length) {
          params.append("categories[]", categories);
        }

        if (includedArr.length) {
          params.append("included[]", includedArr);
        }

        if (excludedArr.length) {
          params.append("excluded[]", excludedArr);
        }

        return params;
      }

      return await exportPoints(getParams(), region, dbTable);
    },
    {
      enabled,
      onSuccess: handleExportSuccess,
      onSettled,
      retry: false,
    }
  );
};
