"use server";

import postData from "@/api/post-data";
import fetchData from "../fetch-data";
import updateQuantity from "./update-quantity";

export default async function addToCart(id, quantity = 1, feature) {
  const { error, data } = await fetchData({
    endPoint: "/cart/items",
  });


  if (!error) {
    const isExist = data?.products?.find((item) => item.id === id);
    if (isExist) {
      // If the product is already in the cart, update its quantity
      return await updateQuantity(id, Number(isExist.quantity) + quantity);
    }
  }


  // If the product is not in the cart, add it with quantity 1
  const formData = new FormData();
  formData.append("item_id", id);
  formData.append("item_quantity", quantity);

  if (feature) {
    if (feature.type === 'color') {
      formData.append('color', feature.id);
    } else {
      formData.append('size', feature.id);
    }
  }

  const res = await postData({
    endPoint: "/cart/add/item",
    body: formData,
  });
  if (res.error) {
    return res;
  }

  return res;
}
