import { apiClient, getDataOrThrow } from "@/core/api";
import {
  checkoutSessionResponseSchema,
  type CheckoutCart,
  type CheckoutSessionResponse,
  type OrderConfigurations,
  type OrderSelections,
  type OrderTypeValue,
} from "@customer-portal/domain/orders";

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<CheckoutCart>("/api/checkout/cart", {
      body: {
        orderType,
        selections,
        configuration,
      },
    });

    return getDataOrThrow(response, "Failed to build checkout cart");
  },

  async createSession(
    orderType: OrderTypeValue,
    selections: OrderSelections,
    configuration?: OrderConfigurations
  ): Promise<CheckoutSessionResponse> {
    const response = await apiClient.POST<CheckoutSessionResponse>("/api/checkout/session", {
      body: { orderType, selections, configuration },
    });
    const data = getDataOrThrow(response, "Failed to create checkout session");
    return checkoutSessionResponseSchema.parse(data);
  },

  async getSession(sessionId: string): Promise<CheckoutSessionResponse> {
    const response = await apiClient.GET<CheckoutSessionResponse>(
      "/api/checkout/session/{sessionId}",
      {
        params: { path: { sessionId } },
      }
    );
    const data = getDataOrThrow(response, "Failed to load checkout session");
    return checkoutSessionResponseSchema.parse(data);
  },

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