import { apiCall } from "@/utils/callApi";

// Types

type CartIdentifier =
  | { user: string; guestId?: never }
  | { guestId: string; user?: never };

type CartItem = {
  productId: string;
  skuId: string | null;
  quantity: number;
};

// GET Cart

export function getCart(identifier: CartIdentifier) {
  const query =
    "user" in identifier && identifier.user
      ? `?user=${identifier.user}`
      : `?guestId=${identifier.guestId}`;

  return apiCall<any>(`/clientapi/cart${query}`);
}

// ADD to Cart (POST)

export function addToCart(identifier: CartIdentifier, item: CartItem) {
  return apiCall<any>("/clientapi/cart", {
    method: "POST",
    body: { ...identifier, ...item },
  });
}

// UPDATE Cart Item (PUT)

export function updateCartItem(
  identifier: CartIdentifier,
  skuId: string,
  quantity: number
) {
  return apiCall<any>("/clientapi/cart", {
    method: "PUT",
    body: { ...identifier, skuId, quantity },
  });
}

// REMOVE Cart Item (DELETE)

export function removeFromCart(identifier: CartIdentifier, skuId: string) {
  return apiCall<any>("/clientapi/cart", {
    method: "DELETE",
    body: { ...identifier, skuId },
  });
}
export function clearFromCart(identifier: CartIdentifier, guestId?: string) {
  return apiCall<any>("/clientapi/cart", {
    method: "DELETE",
    body: { ...identifier,guestId },
  });
}