import axios from "axios";

export const BASE_URL = import.meta.env.VITE_API_URL;

export const api = axios.create({
  baseURL:
    import.meta.env.MODE === "development"
      ? "http://localhost:5173/"
      : BASE_URL,
});

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

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

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

  return resultParams;
};

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

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

  return data;
};

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

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

  return data;
};

export const downloadImportTemplate = async (dataType) => {
  const { data } = await api.get(
    `/default_data/templates/${dataType}.xlsx`,
    { responseType: "arraybuffer" }
  );

  return data;
};

export const uploadPointsFile = async (file, dataType, refill = false,) => {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("model", dataType);
  formData.append("refill", refill);
  const { data } = await api.post(
    `/api/import_file/`,
    formData
  );

  return data;
};

export const startAnalysis = async () => {
  const { data } = await api.get(`/api/data/start_ds_miracle`);

  return data;
};
