import type { ShopOrderGoods } from '@/api/shop/shopOrderGoods/model';

/**
 * Normalize order goods data returned by the order/page API.
 *
 * In practice different backends may return different field names (orderGoods/orderGoodsList/goodsList...),
 * and the item fields can also differ (goodsName/title/name, totalNum/quantity, etc.).
 *
 * We normalize them to ShopOrderGoods so list pages can render without doing N+1 requests per order.
 */
export const normalizeOrderGoodsList = (order: any): ShopOrderGoods[] => {
  const raw =
    order?.orderGoods ||
    order?.orderGoodsList ||
    order?.goodsList ||
    order?.goods ||
    [];
  if (!Array.isArray(raw)) return [];

  return raw.map((g: any) => ({
    ...g,
    goodsId: g?.goodsId ?? g?.itemId ?? g?.goods_id,
    skuId: g?.skuId ?? g?.sku_id,
    // When the API returns minimal fields, fall back to order title to avoid blank names.
    goodsName: g?.goodsName ?? g?.goodsTitle ?? g?.title ?? g?.name ?? order?.title ?? '商品',
    image: g?.image ?? g?.goodsImage ?? g?.cover ?? g?.pic,
    spec: g?.spec ?? g?.specInfo ?? g?.spec_name,
    totalNum: g?.totalNum ?? g?.quantity ?? g?.num ?? g?.count,
    price: g?.price ?? g?.payPrice ?? g?.goodsPrice ?? g?.unitPrice
  }));
};

