import { apiClient, getDataOrThrow } from "@/lib/api";
import type {
  CheckoutCart,
  OrderConfigurations,
  OrderSelections,
  OrderTypeValue,
} from "@customer-portal/domain/orders";
import type { ApiSuccessResponse } from "@customer-portal/domain/common";

export const checkoutService = {
  /**
   * Build checkout cart from order type and selections
   */
  async buildCart(
    orderType: OrderTypeValue,
    selections: OrderSelections,
    configuration?: OrderConfigurations
  ): Promise<CheckoutCart> {
    const response = await apiClient.POST<ApiSuccessResponse<CheckoutCart>>("/api/checkout/cart", {
      body: {
        orderType,
        selections,
        configuration,
      },
    });

    const wrappedResponse = getDataOrThrow(response, "Failed to build checkout cart");
    if (!wrappedResponse.success) {
      throw new Error("Failed to build checkout cart");
    }
    return wrappedResponse.data;
  },

  /**
   * Validate checkout cart
   */
  async validateCart(cart: CheckoutCart): Promise<void> {
    await apiClient.POST("/api/checkout/validate", { body: cart });
  },
};
