import { listOrderItemsByOrderId } from '../../repositories/order-item-repo.js'
import { listTasksByOrderId } from '../../repositories/task-repo.js'
import { formatFenToAmount, normalizeFen } from '../../utils/money.js'
import { resolveDisplayShopName, resolveOrderItemTitle } from './admin-read-shared-helpers.js'
import { buildOrderBindingSummary, getTaskBindingSummaryMap } from './admin-task-read-helpers.js'

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

export async function mapAdminOrderListItem(item: OrderListRow): Promise<AdminOrderListItem> {
  const [tasks, orderItems] = await Promise.all([
    listTasksByOrderId(item.id),
    listOrderItemsByOrderId(item.id),
  ])
  const taskBindingSummaryMap = await getTaskBindingSummaryMap(tasks.map((task) => task.id))
  const bindingSummary = buildOrderBindingSummary(tasks, taskBindingSummaryMap)
  const itemSummary = summarizeOrderItems(orderItems)

  return {
    orderId: item.id,
    provider: item.provider || 'agiso',
    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: Number(item.task_count || tasks.length || 0),
    systemBindingStatus: bindingSummary.systemBindingStatus,
    userBindingStatus: bindingSummary.userBindingStatus,
    systemBoundTaskCount: bindingSummary.systemBoundTaskCount,
    completedBindingTaskCount: bindingSummary.completedBindingTaskCount,
    totalBindingCount: bindingSummary.totalBindingCount,
    reservedBindingCount: bindingSummary.reservedBindingCount,
    consumedBindingCount: bindingSummary.consumedBindingCount,
    releasedBindingCount: bindingSummary.releasedBindingCount,
  }
}

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} 项`
}
