import { handleError, handleSuccess } from ".";
import axios from "../lib/axios";
import { IScrapConfig, IWebBid } from "../system/type";
import { removeFalsyValues } from "../utils";

export const createScrapConfig = async (
  bid: Omit<
    IScrapConfig,
    "id" | "created_at" | "updated_at" | "scrap_items"
  > & { web_id: IWebBid["id"] }
) => {
  const newData = removeFalsyValues(bid);

  try {
    const { data } = await axios({
      url: "scrap-configs",
      withCredentials: true,
      method: "POST",
      data: {
        ...newData,
        enable: newData.enable === "1",
      },
    });

    handleSuccess(data);

    return data;
  } catch (error) {
    handleError(error);
  }
};

export const updateScrapConfig = async (scrapConfig: Partial<IScrapConfig>) => {
  const { search_url, keywords, id, enable } = removeFalsyValues(scrapConfig);

  try {
    const { data } = await axios({
      url: "scrap-configs/" + id,
      withCredentials: true,
      method: "PUT",
      data: { search_url, keywords, enable: enable === "1" },
    });

    handleSuccess(data);

    return data;
  } catch (error) {
    handleError(error);
  }
};
