import axios from "axios";
import { useQuery } from "@tanstack/react-query";
import { STATUSES } from "./config";
import { useFilters } from "./stores/useFilters";
import { usePointSelection } from "./stores/usePointSelection";

export const BASE_URL = "https://postnet-dev.selftech.ru";

export const api = axios.create({
  baseURL:
    import.meta.env.MODE === "development"
      ? "http://localhost:5173/"
      : `${BASE_URL}/`,
  withCredentials: true,
  xsrfHeaderName: "X-CSRFToken",
  xsrfCookieName: "csrftoken",
});

const enrichParamsWithRegionFilter = (params, region) => {
  const resultParams = params ? params : new URLSearchParams();

  if (region) {
    if (region.type === "ao") {
      resultParams.append("ao[]", region.id);
    }

    if (region.type === "rayon") {
      resultParams.append("rayon[]", region.id);
    }
  }

  return resultParams;
};

export const getPoints = async (params, region) => {
  const resultParams = enrichParamsWithRegionFilter(params, region);

  const { data } = await api.get(
    `/api/placement_points?${resultParams.toString()}`
  );

  return data;
};

export const exportPoints = async (params, region) => {
  const resultParams = enrichParamsWithRegionFilter(params, region);

  const { data } = await api.get(
    `/api/placement_points/to_excel?${resultParams.toString()}`,
    { responseType: "arraybuffer" }
  );

  return data;
};

export const useGetTotalInitialPointsCount = () => {
  return useQuery(
    ["all-initial-count"],
    async () => {
      const params = new URLSearchParams({
        page: 1,
        page_size: 1,
        "status[]": [STATUSES.initial],
      });

      return await getPoints(params);
    },
    { select: (data) => data.count }
  );
};

export const useGetFilteredInitialPointsCount = () => {
  const { filters } = useFilters();
  const { prediction, categories, region } = filters;
  const {
    selection: { included },
  } = usePointSelection();

  const includedIds = [...included];

  return useQuery(
    ["filtered-points", filters, includedIds],
    async () => {
      const params = new URLSearchParams({
        page: 1,
        page_size: 1,
        "prediction_current[]": prediction,
        "status[]": [STATUSES.initial],
        "categories[]": categories,
        "included[]": includedIds,
      });

      return await getPoints(params, region);
    },
    { select: (data) => data.count, keepPreviousData: true }
  );
};
