import { formatFenToAmount, normalizeFen } from '../../utils/money.js'
import { resolveDisplayShopName, resolveOrderItemTitle } from './admin-read-shared-helpers.js'
import { buildOrderFulfillmentProgress } from './admin-task-read-helpers.js'

import type { AdminOrderListItem } from '../../types/admin/read-models.js'
import type { OrderItemRow, OrderListRow, TaskRow } from '../../types/repository/rows.js'

export function mapAdminOrderListItem(
  item: OrderListRow,
  { tasks = [], orderItems = [] }: { tasks?: TaskRow[]; orderItems?: OrderItemRow[] } = {},
): AdminOrderListItem {
  const fulfillmentProgress = buildOrderFulfillmentProgress(tasks)
  const itemSummary = summarizeOrderItems(orderItems)

  return {
    orderId: item.id,
    provider: item.provider || '',
    platform: item.platform,
    shopId: item.shop_id || '',
    shopName: resolveDisplayShopName(item.provider, item.shop_id, item.shop_name),
    platformOrderId: item.platform_order_id,
    orderStatus: item.order_status,
    payStatus: item.pay_status,
    buyerId: item.buyer_id || '',
    buyerName: item.buyer_name,
    receiverContact: item.receiver_contact || '',
    totalAmount: formatFenToAmount(item.total_amount),
    totalAmountFen: normalizeFen(item.total_amount),
    currency: item.currency,
    paidAt: item.paid_at,
    createdAt: item.created_at,
    updatedAt: item.updated_at,
    itemCount: orderItems.length,
    totalQuantity: orderItems.reduce(
      (sum, orderItem) => sum + Math.max(1, Number(orderItem.quantity || 1)),
      0,
    ),
    itemSummary,
    taskCount: tasks.length,
    resourceStatus: fulfillmentProgress.resourceStatus,
    customerStatus: fulfillmentProgress.customerStatus,
    preparedTaskCount: fulfillmentProgress.preparedTaskCount,
    completedTaskCount: fulfillmentProgress.completedTaskCount,
  }
}

export function summarizeOrderItems(items: OrderItemRow[] | null | undefined): string {
  const normalizedItems = Array.isArray(items) ? items : []

  if (normalizedItems.length === 0) {
    return ''
  }

  const [firstItem] = normalizedItems
  const firstLabel =
    resolveOrderItemTitle(firstItem) ||
    String(firstItem?.sku_name || firstItem?.sku_code || '').trim()

  if (normalizedItems.length === 1) {
    return firstLabel
  }

  return `${firstLabel} 等 ${normalizedItems.length} 项`
}
