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

const BASE_URL = "web-bids";

export const getWebBids = async (params: Record<string, string | number>) => {
  return await axios({
    url: BASE_URL,
    params: generateNestParams(params),
    withCredentials: true,
    method: "GET",
  });
};

export const createWebBid = async (
  bid: Omit<IWebBid, "id" | "created_at" | "updated_at" | "is_system_account">
) => {
  const newData = removeFalsyValues(bid);

  try {
    const { data } = await axios({
      url: BASE_URL,
      withCredentials: true,
      method: "POST",
      data: newData,
    });

    handleSuccess(data);

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

export const updateWebBid = async (bid: Partial<IWebBid>) => {
  const {
    url,
    password,
    username,
    origin_url,
    active,
    arrival_offset_seconds,
    early_tracking_seconds
  } = removeFalsyValues(bid, ["active"]);

  try {
    const { data } = await axios({
      url: `${BASE_URL}/` + bid.id,
      withCredentials: true,
      method: "PUT",
      data: {
        url,
        password,
        username,
        origin_url,
        active,
        arrival_offset_seconds,
        early_tracking_seconds
      },
    });

    handleSuccess(data);

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

export const deleteWebBid = async (web: IWebBid) => {
  try {
    const { data } = await axios({
      url: `${BASE_URL}/` + web.id,
      withCredentials: true,
      method: "DELETE",
    });

    handleSuccess(data);

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

export const deletesWebBid = async (web: IWebBid[]) => {
  const ids = web.reduce((prev, cur) => {
    prev.push(cur.id);
    return prev;
  }, [] as number[]);
  try {
    const { data } = await axios({
      url: `${BASE_URL}/deletes`,
      withCredentials: true,
      method: "POST",
      data: {
        ids,
      },
    });

    handleSuccess(data);

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