import { apiClient } from "@/lib/api";
import { log } from "@/lib/logger";
import {
  orderDetailsSchema,
  orderSummarySchema,
  type CreateOrderRequest,
  type OrderDetails,
  type OrderSummary,
} from "@customer-portal/domain/orders";
import { assertSuccess, type DomainApiResponse } from "@/lib/api/response-helpers";

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

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

  try {
    const response = await apiClient.POST("/api/orders", { body });

    const parsed = assertSuccess<{ sfOrderId: string; status: string; message: string }>(
      response.data as DomainApiResponse<{ sfOrderId: string; status: string; message: string }>
    );
    return { sfOrderId: parsed.data.sfOrderId };
  } catch (error) {
    log.error(
      "Order creation failed",
      error instanceof Error ? error : undefined,
      {
        orderType: body.orderType,
        skuCount: body.skus.length,
      }
    );
    throw error;
  }
}

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 } },
    signal: options.signal,
  });
  if (!response.data) {
    throw new Error("Order not found");
  }
  return orderDetailsSchema.parse(response.data);
}

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