import { fetchWrapper } from "../fetchWrapper";
import { removeEmptyFields, checkChangeData } from "./changesObjects";

export function getRequestChangeData(
  createData,
  updateData,
  initData,
  key,
  id
) {
  let isInitDataEmpty = [...Object.keys(removeEmptyFields(initData))].length;
  if (Object.keys(removeEmptyFields(updateData)).length) {
    if (!isInitDataEmpty) {
      return fetchWrapper.post(
        `general/${key}/create/`,
        removeEmptyFields(createData)
      );
    }
    if (JSON.stringify(updateData) !== JSON.stringify(initData)) {
      return fetchWrapper.post(
        `general/${key}/${id}/update/`,
        removeEmptyFields(updateData)
      );
    }
    return Promise.resolve();
  }
  return Promise.resolve();
}

export function getRequestArrayData(
  initData,
  updateData,
  updateName,
  idUpdateName,
  api,
  key
) {
  const deleteRequests = initData
    .filter((el) => !updateData.find((data) => data.id === el.id))
    .map((el) => fetchWrapper.del(`${api}/${key}/${el.id}/delete/`));
  const requests = updateData.map((el) => {
    const requestObj = {
      [updateName]: idUpdateName,
      ...el,
    };
    delete requestObj.id;
    if (!el?.id) {
      return fetchWrapper.post(`${api}/${key}/create/`, { ...requestObj });
    }
    if (
      el?.id &&
      checkChangeData(
        initData.find((obj) => obj.id === el.id),
        el
      )
    ) {
      return fetchWrapper.post(`${api}/${key}/${el.id}/update/`, {
        ...requestObj,
      });
    }
    return Promise.resolve();
  });
  return requests.concat(deleteRequests);
}
