import { apiClient, getDataOrThrow } from "@/core/api";
import { logger } from "@/core/logger";
import {
  orderDetailsSchema,
  orderSummarySchema,
  type CreateOrderRequest,
  type OrderDetails,
  type OrderSummary,
} from "@customer-portal/domain/orders";

interface CreateOrderResponse {
  sfOrderId: string;
  status: string;
  message: string;
}

async function createOrder(payload: CreateOrderRequest): Promise<{ sfOrderId: string }> {
  const body: CreateOrderRequest = {
    orderType: payload.orderType,
    skus: payload.skus,
    ...(payload.configurations ? { configurations: payload.configurations } : {}),
  };

  logger.debug("Creating order", {
    orderType: body.orderType,
    skuCount: body.skus.length,
    hasConfigurations: !!body.configurations,
  });

  try {
    const response = await apiClient.POST<CreateOrderResponse>("/api/orders", { body });
    const data = getDataOrThrow(response, "Failed to create order");
    return { sfOrderId: data.sfOrderId };
  } catch (error) {
    logger.error("Order creation failed", error instanceof Error ? error : undefined, {
      orderType: body.orderType,
      skuCount: body.skus.length,
    });
    throw error;
  }
}

async function createOrderFromCheckoutSession(
  checkoutSessionId: string
): Promise<{ sfOrderId: string }> {
  const response = await apiClient.POST<CreateOrderResponse>("/api/orders/from-checkout-session", {
    body: { checkoutSessionId },
  });
  const data = getDataOrThrow(response, "Failed to create order");
  return { sfOrderId: data.sfOrderId };
}

async function getMyOrders(): Promise<OrderSummary[]> {
  const response = await apiClient.GET("/api/orders/user");
  const data = Array.isArray(response.data) ? response.data : [];
  return data.map(item => orderSummarySchema.parse(item));
}

type GetOrderByIdOptions = {
  signal?: AbortSignal;
};

async function getOrderById(
  orderId: string,
  options: GetOrderByIdOptions = {}
): Promise<OrderDetails> {
  const response = await apiClient.GET("/api/orders/{sfOrderId}", {
    params: { path: { sfOrderId: orderId } },
    ...(options.signal ? { signal: options.signal } : {}),
  });
  if (!response.data) {
    throw new Error("Order not found");
  }
  return orderDetailsSchema.parse(response.data);
}

export const ordersService = {
  createOrder,
  createOrderFromCheckoutSession,
  getMyOrders,
  getOrderById,
} as const;
