import { FormsSheetApi } from "../api/form_sheet";
import { ProjectsApi } from "../api/projects";
import { TasksApi } from "../api/tasks";
import { downloadFile } from "./downloadFile";
import { getApiErrorMessage } from "./getApiErrorMessage";
import { toast } from "react-toastify";

export const exportSingleForm = async (taskId, taskTitle) => {
  try {
    const response = await TasksApi.exportTask(taskId);
    await downloadFile(response, taskTitle, "xlsx");
  } catch (error) {
    const message = await getApiErrorMessage(
      error,
      "Ошибка при скачивании файла",
    );
    toast.error(message);
  }
};

export const exportSheet = async (formId, sheetName, direction) => {
  try {
    const normalizedDirection =
      direction && direction !== "null" ? direction : undefined;
    const params = normalizedDirection
      ? { direction: normalizedDirection }
      : {};
    const response = await FormsSheetApi.export(formId, sheetName, params);
    await downloadFile(response, sheetName, "xlsx");
  } catch (error) {
    const message = await getApiErrorMessage(
      error,
      "Ошибка при скачивании файла",
    );
    toast.error(message);
  }
};

export const exportSheetProject = async (formId, sheetName, year) => {
  try {
    const response = await ProjectsApi.export(formId, year, sheetName);
    await downloadFile(response, sheetName, "xlsx");
  } catch (error) {
    const message = await getApiErrorMessage(
      error,
      "Ошибка при скачивании файла",
    );
    toast.error(message);
  }
};

export const exportBulkForms = async (formIds, fileName = "Задачи") => {
  try {
    const response = await TasksApi.exportTasks({ form_ids: formIds });
    await downloadFile(response, fileName, "xlsx");
  } catch (error) {
    const message = await getApiErrorMessage(
      error,
      "Ошибка при скачивании файла",
    );
    toast.error(message);
    throw error;
  }
};
