import assert from 'node:assert/strict'
import test from 'node:test'

import type {
  WorkOrderRow,
  WorkOrderShareRow,
  WorkProductRuleMappingRow,
  WorkProductRuleRow,
  WorkerFinanceRequestRow,
  WorkerUserRow,
  WorkerWalletLedgerRow,
} from '../../repositories/worker-platform/index.js'
import {
  buildWorkOrderWhere,
  resolveWorkOrderShareCancellationStatus,
  resolveWorkOrderShareDepositAmount,
  resolveWorkOrderSharingCancellationPlan,
  resolveWorkOrderShareJoinQuantity,
  resolveOpenSharingSyncReward,
} from '../../repositories/worker-platform/index.js'
import { resolveProblemReturnToWorkerStatus } from '../../repositories/worker-platform/work-order-issue-repo.js'
import type { OrderItemRow, OrderRow } from '../../types/repository/rows.js'
import {
  assertWithdrawChannelAllowedForAmount,
  assertWorkerLoginAllowed,
  canWorkerAutoAcceptWholeOrder,
  isWorkOrderSharingFilled,
  isWorkerPasswordStrong,
  normalizeWithdrawChannel,
  normalizeRequirementFields,
  normalizeWorkerFreezeReason,
  mapWorkOrderForWorker,
  mapWorkOrderAdmin,
  mapWorkOrderSharingWorkers,
  mapFinanceRequest,
  mapWalletLedger,
  maskWorkerLeaderboardDisplayName,
  resolveCollectSubmitTargetWorkOrder,
  resolveAdminMaterialRewardAmount,
  resolveFreezeDepositAmount,
  resolveAdminMockWorkOrderInput,
  resolveMatchingProductRuleDecision,
  resolveWorkerPermissions,
  resolveSkuNameQuantity,
  resolveWorkOrderRulePricing,
  resolveWorkOrderTemplateSyncPrice,
  resolveWorkerShareStatus,
  resolveWorkOrderSharingEnabled,
  validateWorkerPassword,
} from './index.js'
import { resolveAfterSalesRecoveryAllocation } from '../../repositories/worker-platform/after-sales-recovery.js'

test('售后追缴优先扣减待解冻押金', () => {
  assert.deepEqual(
    resolveAfterSalesRecoveryAllocation({
      recoveryAmount: 10_000,
      pendingDepositAmount: 12_000,
      availableAmount: 8_000,
    }),
    {
      pendingDepositDeductionAmount: 10_000,
      availableDeductionAmount: 0,
      debtAmount: 0,
    },
  )
})

test('售后追缴在押金不足时继续扣减可用余额', () => {
  assert.deepEqual(
    resolveAfterSalesRecoveryAllocation({
      recoveryAmount: 10_000,
      pendingDepositAmount: 3_000,
      availableAmount: 8_000,
    }),
    {
      pendingDepositDeductionAmount: 3_000,
      availableDeductionAmount: 7_000,
      debtAmount: 0,
    },
  )
})

test('售后追缴在余额不足时形成欠款', () => {
  assert.deepEqual(
    resolveAfterSalesRecoveryAllocation({
      recoveryAmount: 10_000,
      pendingDepositAmount: 3_000,
      availableAmount: 2_000,
    }),
    {
      pendingDepositDeductionAmount: 3_000,
      availableDeductionAmount: 2_000,
      debtAmount: 5_000,
    },
  )
})

function buildOrderItemRow(): OrderItemRow {
  return {
    id: 1,
    order_id: 1,
    sku_code: '25677565592936',
    sku_name: '1个精英尊尚专属礼盒',
    quantity: 1,
    spec_json: {},
    item_snapshot_json: {
      kuaishouSendCode: {
        sellerId: '3676797936',
        itemId: '25677565592936',
        itemTitle: '和平精英密钥指挥官特种兵侦察兵密钥',
        skuId: '189872452606936',
        relItemId: '25677565592936',
        relSkuId: '',
        skuNick: '1个精英尊尚专属礼盒',
      },
    },
  }
}

function buildOrderRow(): OrderRow {
  return {
    id: 1,
    provider: '91kaquan',
    platform: 'kuaishou',
    shop_id: '3676797936',
    shop_name: '测试店铺',
    platform_order_id: '2623001922675146',
    order_status: 'paid',
    pay_status: 'paid',
    buyer_id: '',
    buyer_name: '',
    receiver_contact: '',
    total_amount: 12600,
    currency: 'CNY',
    raw_payload_json: {},
    paid_at: null,
    created_at: '2026-08-18T00:00:00.000Z',
    updated_at: '2026-08-18T00:00:00.000Z',
  }
}

function buildProductRule(overrides: Partial<WorkProductRuleRow> = {}): WorkProductRuleRow {
  return {
    id: 1,
    rule_key: 'rule-1',
    provider: '91kaquan',
    platform: 'kuaishou',
    shop_id: '',
    sku_code: '',
    product_name: '和平精英',
    match_type: 'contains',
    category_id: null,
    enabled: true,
    auto_create: true,
    reward_amount: 2500,
    unit_price_fen: 0,
    required_deposit_amount: 0,
    deposit_threshold_amount: 20000,
    sharing_enabled: false,
    sharing_total_quantity: 1,
    sharing_unit_reward: 0,
    sharing_auto_from_order: false,
    timeout_minutes: 0,
    timeout_policy: 'reopen',
    requirement_json: {},
    match_json: {},
    sort_order: 100,
    created_at: '2026-08-18T00:00:00.000Z',
    updated_at: '2026-08-18T00:00:00.000Z',
    ...overrides,
  }
}

function buildProductMapping(
  overrides: Partial<WorkProductRuleMappingRow> = {},
): WorkProductRuleMappingRow {
  return {
    id: 1,
    rule_id: 1,
    seller_ids_json: ['3676797936'],
    rel_item_id: '25677565592936',
    item_title: '和平精英密钥指挥官特种兵侦察兵密钥',
    rel_sku_id: '',
    sku_nick: '',
    sku_match_mode: 'fuzzy',
    mapping_type: 'product_default',
    enabled: true,
    created_at: '2026-08-18T00:00:00.000Z',
    updated_at: '2026-08-18T00:00:00.000Z',
    ...overrides,
  }
}

function buildWorkerUserRow(overrides: Partial<WorkerUserRow> = {}): WorkerUserRow {
  return {
    id: 1,
    username: 'jd01',
    password_hash: 'scrypt$salt$hash',
    display_name: '测试打手',
    phone: '',
    level_id: 1,
    status: 'active',
    review_note: '',
    session_version: 1,
    created_at: '2026-07-28T00:00:00.000Z',
    updated_at: '2026-07-28T00:00:00.000Z',
    reviewed_at: null,
    inviter_id: null,
    invite_code: 'TEST0001',
    ...overrides,
  }
}

test('assertWorkerLoginAllowed allows active workers', () => {
  assert.doesNotThrow(() => assertWorkerLoginAllowed(buildWorkerUserRow()))
})

test('接单密码至少八位且必须包含英文字母和数字', () => {
  assert.equal(isWorkerPasswordStrong('abc12345'), true)
  assert.equal(isWorkerPasswordStrong('ABC12345'), true)
  assert.equal(isWorkerPasswordStrong('12345678'), false)
  assert.equal(isWorkerPasswordStrong('abcdefgh'), false)
  assert.equal(isWorkerPasswordStrong('abc1234'), false)
  assert.doesNotThrow(() => validateWorkerPassword('abc12345'))
  assert.throws(() => validateWorkerPassword('12345678'), { errorCode: 'worker_password_invalid' })
})

test('本地 Mock 工单要求订单、店铺、商品与两个金额完整有效', () => {
  const shops = [
    {
      enabled: true,
      sellerId: 'seller-1',
      shopId: 'shop-1',
      shopName: '测试店铺',
      customShopName: '',
      authState: '',
      accessToken: '',
      refreshToken: '',
      accessTokenExpiresAt: '',
      refreshTokenExpiresAt: '',
      openId: '',
      grantedScopes: '',
      lastRefreshedAt: '',
      lastRefreshError: '',
    },
    {
      enabled: false,
      sellerId: 'seller-disabled',
      shopId: 'shop-disabled',
      shopName: '已停用店铺',
      customShopName: '',
      authState: '',
      accessToken: '',
      refreshToken: '',
      accessTokenExpiresAt: '',
      refreshTokenExpiresAt: '',
      openId: '',
      grantedScopes: '',
      lastRefreshedAt: '',
      lastRefreshError: '',
    },
  ]
  const baseInput = {
    platformOrderId: 'MOCK-1',
    productName: '测试商品',
    sellerId: 'seller-1',
    rewardAmount: 25,
    paymentAmount: 30,
  }

  assert.throws(() => resolveAdminMockWorkOrderInput({}, shops), {
    errorCode: 'mock_work_order_no_required',
  })
  assert.throws(() => resolveAdminMockWorkOrderInput({ platformOrderId: 'MOCK-1' }, shops), {
    errorCode: 'mock_work_order_product_name_required',
  })
  assert.throws(
    () =>
      resolveAdminMockWorkOrderInput({ platformOrderId: 'MOCK-1', productName: '测试商品' }, shops),
    { errorCode: 'mock_work_order_shop_required' },
  )
  // 未命中已配置店铺时按自定义店铺放行，便于其他平台订单手动录入
  {
    const customShop = resolveAdminMockWorkOrderInput(
      { ...baseInput, sellerId: '抖音自定义小店' },
      shops,
    )
    assert.equal(customShop.shop.shopName, '抖音自定义小店')
    assert.equal(customShop.shop.sellerId, '')
  }
  assert.throws(
    () => resolveAdminMockWorkOrderInput({ ...baseInput, sellerId: 'seller-disabled' }, shops),
    { errorCode: 'mock_work_order_shop_disabled' },
  )
  assert.throws(
    () => resolveAdminMockWorkOrderInput({ ...baseInput, rewardAmount: undefined }, shops),
    { errorCode: 'mock_work_order_reward_amount_required' },
  )
  assert.throws(() => resolveAdminMockWorkOrderInput({ ...baseInput, paymentAmount: 0 }, shops), {
    errorCode: 'mock_work_order_payment_amount_invalid',
  })
  assert.deepEqual(resolveAdminMockWorkOrderInput(baseInput, shops).rewardAmount, 2500)
})

test('排行榜打手名称仅展示首字符', () => {
  assert.equal(maskWorkerLeaderboardDisplayName('张三'), '张****')
  assert.equal(maskWorkerLeaderboardDisplayName('Alice'), 'A****')
  assert.equal(maskWorkerLeaderboardDisplayName(''), '****')
})

test('开启旧规则兼容匹配后，快手具体 SKU 精确规则优先于大标题包含规则', () => {
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    buildOrderItemRow(),
    [
      buildProductRule(),
      buildProductRule({
        id: 2,
        rule_key: 'gift-box',
        product_name: '精英尊尚专属礼盒',
        match_json: {
          sellerId: '3676797936',
          itemTitle: '和平精英密钥指挥官特种兵侦察兵密钥',
          skuNick: '1个精英尊尚专属礼盒',
          itemTitleMatchType: 'exact',
          skuNickMatchType: 'exact',
        },
      }),
    ],
    [],
    { legacyFallbackEnabled: true },
  )

  assert.equal(decision.reason, 'matched')
  assert.equal(decision.rule?.rule_key, 'gift-box')
})

test('开启旧规则兼容匹配后，快手同优先级精确规则进入冲突状态', () => {
  const match = {
    sellerId: '3676797936',
    skuId: '189872452606936',
  }
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    buildOrderItemRow(),
    [
      buildProductRule({ rule_key: 'gift-box-a', match_json: match }),
      buildProductRule({ id: 2, rule_key: 'gift-box-b', match_json: match }),
    ],
    [],
    { legacyFallbackEnabled: true },
  )

  assert.equal(decision.reason, 'ambiguous')
  assert.equal(decision.rule, null)
})

test('快手订单默认不使用旧模板大标题匹配', () => {
  const decision = resolveMatchingProductRuleDecision(buildOrderRow(), buildOrderItemRow(), [
    buildProductRule({ rule_key: 'special-soldier', product_name: '特种兵' }),
  ])

  assert.equal(decision.reason, 'unmatched')
  assert.equal(decision.rule, null)
  assert.deepEqual(decision.candidates, [])
})

test('快手 SKU 覆盖映射优先于商品默认映射', () => {
  const defaultRule = buildProductRule({ rule_key: 'commander-default', product_name: '' })
  const skuRule = buildProductRule({ id: 2, rule_key: 'gift-box-sku', product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    buildOrderItemRow(),
    [defaultRule, skuRule],
    [
      buildProductMapping({ rule_id: defaultRule.id }),
      buildProductMapping({
        id: 2,
        rule_id: skuRule.id,
        rel_sku_id: '',
        sku_nick: '1个精英尊尚专属礼盒',
        mapping_type: 'sku_exact',
      }),
    ],
  )

  assert.equal(decision.reason, 'matched')
  assert.equal(decision.rule?.rule_key, 'gift-box-sku')
  assert.equal(decision.mappingId, 2)
})

test('SKU 数量系列可覆盖多店铺的前后数量规格', () => {
  const order = buildOrderRow()
  order.shop_id = '3676797937'
  const item = buildOrderItemRow()
  item.sku_name = '指挥官密钥10个'
  item.item_snapshot_json = {
    kuaishouSendCode: {
      sellerId: '3676797937',
      itemId: '26765374805642',
      itemTitle: '和平精英密钥指挥官特种兵侦察兵密钥',
      skuId: '189872452606936',
      relItemId: '26765374805642',
      relSkuId: '',
      skuNick: '指挥官密钥10个',
    },
  }
  const rule = buildProductRule({ rule_key: 'commander-series', product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    order,
    item,
    [rule],
    [
      buildProductMapping({
        rule_id: rule.id,
        seller_ids_json: ['3676797936', '3676797937'],
        rel_item_id: '',
        item_title: '',
        mapping_type: 'sku_series',
        sku_nick: '指挥官密钥',
      }),
    ],
  )

  assert.equal(decision.reason, 'matched')
  assert.equal(decision.rule?.rule_key, 'commander-series')
})

test('SKU 数量系列默认模糊匹配密钥和秘钥', () => {
  const item = buildOrderItemRow()
  item.item_snapshot_json = {
    kuaishouSendCode: {
      ...item.item_snapshot_json.kuaishouSendCode,
      skuNick: '指挥官秘钥8个',
    },
  }
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    item,
    [rule],
    [
      buildProductMapping({
        mapping_type: 'sku_series',
        sku_nick: '指挥官密钥',
      }),
    ],
  )

  assert.equal(decision.reason, 'matched')
})

test('SKU 数量系列精确匹配不兼容密钥和秘钥', () => {
  const item = buildOrderItemRow()
  item.item_snapshot_json = {
    kuaishouSendCode: {
      ...item.item_snapshot_json.kuaishouSendCode,
      skuNick: '指挥官秘钥8个',
    },
  }
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    item,
    [rule],
    [
      buildProductMapping({
        mapping_type: 'sku_series',
        sku_nick: '指挥官密钥',
        sku_match_mode: 'exact',
      }),
    ],
  )

  assert.equal(decision.reason, 'unmatched')
})

test('商品默认映射支持用逗号填写多个关联商品 ID', () => {
  const item = buildOrderItemRow()
  item.item_snapshot_json = {
    kuaishouSendCode: {
      ...item.item_snapshot_json.kuaishouSendCode,
      relItemId: '26765374805642',
    },
  }
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    item,
    [rule],
    [
      buildProductMapping({
        rel_item_id: '25677565592936, 26765374805642',
      }),
    ],
  )

  assert.equal(decision.reason, 'matched')
  assert.equal(decision.rule?.id, rule.id)
})

test('商品默认映射配置商品 ID 时，订单缺少商品 ID 不应误命中', () => {
  const item = buildOrderItemRow()
  item.item_snapshot_json = {
    kuaishouSendCode: {
      ...item.item_snapshot_json.kuaishouSendCode,
      relItemId: '',
    },
  }
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    item,
    [rule],
    [
      buildProductMapping({
        rel_item_id: '26765374805642',
        item_title: '',
      }),
    ],
  )

  assert.equal(decision.reason, 'unmatched')
  assert.equal(decision.rule, null)
})

test('SKU 数量系列不会按公共词误匹配其他系列', () => {
  const item = buildOrderItemRow()
  item.sku_name = '指挥官隐藏款1个'
  item.item_snapshot_json = {
    kuaishouSendCode: {
      sellerId: '3676797936',
      itemId: '25677565592936',
      itemTitle: '和平精英密钥指挥官特种兵侦察兵密钥',
      skuId: '189872452606936',
      relItemId: '25677565592936',
      relSkuId: '',
      skuNick: '指挥官隐藏款1个',
    },
  }
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    item,
    [rule],
    [
      buildProductMapping({
        rule_id: rule.id,
        mapping_type: 'sku_series',
        sku_nick: '指挥官密钥',
      }),
    ],
  )

  assert.equal(decision.reason, 'unmatched')
})

test('商品映射不以公共词包含匹配，完整大标题不同则不命中', () => {
  const rule = buildProductRule({ product_name: '' })
  const decision = resolveMatchingProductRuleDecision(
    buildOrderRow(),
    buildOrderItemRow(),
    [rule],
    [
      buildProductMapping({
        rule_id: rule.id,
        rel_item_id: '',
        item_title: '和平精英指挥官限量礼包',
      }),
    ],
  )

  assert.equal(decision.reason, 'unmatched')
  assert.equal(decision.rule, null)
})

test('assertWorkerLoginAllowed blocks rejected (frozen) workers with worker_rejected', () => {
  assert.throws(
    () => assertWorkerLoginAllowed(buildWorkerUserRow({ status: 'rejected' })),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 403 &&
        (error as { errorCode?: string }).errorCode === 'worker_rejected',
      ),
  )
})

test('冻结账号必须填写原因，并限制原因长度', () => {
  assert.throws(() => normalizeWorkerFreezeReason(''), {
    message: '请填写冻结原因或备注',
  })
  assert.equal(normalizeWorkerFreezeReason('多次超时未完成订单'), '多次超时未完成订单')
  assert.throws(() => normalizeWorkerFreezeReason('a'.repeat(501)), {
    message: '冻结原因不能超过 500 个字符',
  })
})

test('assertWorkerLoginAllowed blocks pending review workers with worker_pending_review', () => {
  assert.throws(
    () => assertWorkerLoginAllowed(buildWorkerUserRow({ status: 'pending_review' })),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 403 &&
        (error as { errorCode?: string }).errorCode === 'worker_pending_review',
      ),
  )
})

test('assertWorkerLoginAllowed blocks disabled workers with worker_disabled', () => {
  assert.throws(
    () => assertWorkerLoginAllowed(buildWorkerUserRow({ status: 'disabled' })),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 403 &&
        (error as { errorCode?: string }).errorCode === 'worker_disabled',
      ),
  )
})

test('微信提现金额不超过 100 元时允许提交', () => {
  assert.doesNotThrow(() => assertWithdrawChannelAllowedForAmount(10_000, 'wechat'))
})

test('微信提现金额超过 100 元时被拒绝', () => {
  assert.throws(
    () => assertWithdrawChannelAllowedForAmount(10_001, 'wechat'),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { errorCode?: string }).errorCode === 'worker_withdraw_channel_amount_limited',
      ),
  )
})

test('支付宝提现申请保留收款二维码快照', () => {
  const request: WorkerFinanceRequestRow = {
    id: 1,
    worker_id: 1,
    request_type: 'withdraw',
    status: 'pending',
    amount: 10_000,
    account_channel: 'alipay',
    account_name: '测试用户',
    account_no: 'test@example.com',
    note: '',
    reviewed_note: '',
    payload_json: {
      alipayQrCodeImage: { url: 'https://example.com/alipay-qr.png' },
    },
    created_at: '2026-08-20T00:00:00.000Z',
    updated_at: '2026-08-20T00:00:00.000Z',
    reviewed_at: null,
    worker_type: 'internal',
    worker_level_key: 'vip5',
    worker_level_name: 'VIP5',
    worker_withdraw_request_count: 3,
    worker_total_withdraw_amount: 28_800,
  }

  const mapped = mapFinanceRequest(request)
  assert.equal(
    (mapped?.payload.alipayQrCodeImage as { url?: string }).url,
    'https://example.com/alipay-qr.png',
  )
  assert.deepEqual(mapped?.worker, {
    workerId: 1,
    username: '',
    displayName: '',
    phone: '',
    workerType: 'internal',
    levelKey: 'vip5',
    levelName: 'VIP5',
    withdrawRequestCount: 3,
    totalWithdrawAmount: 28_800,
  })
})

test('提现渠道仅支持支付宝和微信', () => {
  assert.equal(normalizeWithdrawChannel('alipay'), 'alipay')
  assert.equal(normalizeWithdrawChannel('wechat'), 'wechat')
  assert.throws(() => normalizeWithdrawChannel('bank'))
})

test('等级免审核后补图权限默认关闭，仅显式开启时生效', () => {
  assert.equal(resolveWorkerPermissions(buildWorkerUserRow()).autoAcceptWithoutEvidence, false)
  assert.equal(
    resolveWorkerPermissions(
      buildWorkerUserRow({
        level_permission_json: { autoAcceptWithoutEvidence: true },
      }),
    ).autoAcceptWithoutEvidence,
    true,
  )
})

test('个人免押额度与等级免押额度叠加', () => {
  const worker = buildWorkerUserRow({
    level_permission_json: { depositFreeAmount: 5_000 },
    personal_deposit_free_amount: 12_000,
  })
  const permissions = resolveWorkerPermissions(worker)
  assert.equal(permissions.depositFreeAmount, 17_000)
  assert.equal(permissions.levelDepositFreeAmount, 5_000)
  assert.equal(permissions.personalDepositFreeAmount, 12_000)
  assert.equal(
    resolveFreezeDepositAmount(buildWorkOrderRow({ required_deposit_amount: 20_000 }), permissions),
    3_000,
  )
})

test('拼单按打手累计份额扣除个人免押额度', () => {
  assert.equal(
    resolveWorkOrderShareDepositAmount({
      requiredDepositAmount: 10_000,
      totalQuantity: 10,
      nextQuantity: 5,
      depositFreeAmount: 3_000,
    }),
    2_000,
  )
  assert.equal(
    resolveWorkOrderShareDepositAmount({
      requiredDepositAmount: 10_000,
      totalQuantity: 10,
      nextQuantity: 5,
      depositFreeAmount: 8_000,
      currentFrozenDeposit: 1_500,
    }),
    1_500,
  )
})

test('后台整单指派给 VIP5 时不因母工单保留拼单配置而失去免审核资格', () => {
  const vip5Worker = buildWorkerUserRow({
    level_key: 'vip5',
    level_permission_json: { autoAcceptWithoutEvidence: true },
  })

  assert.equal(
    canWorkerAutoAcceptWholeOrder({ worker: vip5Worker, hasPersonalSharingShare: false }),
    true,
  )
  assert.equal(
    canWorkerAutoAcceptWholeOrder({ worker: vip5Worker, hasPersonalSharingShare: true }),
    false,
  )
})

test('normalizeRequirementFields default template keeps gameId/gameNickname as text inputs', () => {
  const fields = normalizeRequirementFields([])
  const gameId = fields.find((field) => field.key === 'gameId')
  const gameNickname = fields.find((field) => field.key === 'gameNickname')
  assert.equal(gameId?.type, 'text')
  assert.equal(gameId?.required, true)
  assert.deepEqual(gameId?.options, [])
  assert.equal(gameNickname?.type, 'text')
  assert.equal(gameNickname?.required, true)
})

test('normalizeRequirementFields default template renders system as single-select 安卓/苹果 (optional)', () => {
  const fields = normalizeRequirementFields([])
  const system = fields.find((field) => field.key === 'system')
  assert.equal(system?.type, 'select')
  assert.equal(system?.required, false)
  assert.deepEqual(system?.options, ['安卓', '苹果'])
})

test('normalizeRequirementFields default template marks serverZone optional with QQ区/微信区 options', () => {
  const fields = normalizeRequirementFields([])
  const serverZone = fields.find((field) => field.key === 'serverZone')
  assert.equal(serverZone?.type, 'select')
  assert.equal(serverZone?.required, false)
  assert.deepEqual(serverZone?.options, ['QQ区', '微信区'])
})

test('resolveSkuNameQuantity parses arabic quantities from sku names', () => {
  assert.equal(resolveSkuNameQuantity('指挥官秘钥1个'), 1)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥15个'), 15)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥2个'), 2)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥10个'), 10)
})

test('resolveSkuNameQuantity parses chinese numeral quantities from sku names', () => {
  assert.equal(resolveSkuNameQuantity('指挥官秘钥三个'), 3)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥十五个'), 15)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥二十个'), 20)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥三十个'), 30)
})

test('resolveSkuNameQuantity falls back to 1 when no quantity is found', () => {
  assert.equal(resolveSkuNameQuantity('指挥官秘钥'), 1)
  assert.equal(resolveSkuNameQuantity(''), 1)
  assert.equal(resolveSkuNameQuantity('指挥官秘钥礼包'), 1)
})

test('按件拼单未手动覆盖时，使用匹配数量与模板单价', () => {
  const pricing = resolveWorkOrderRulePricing({
    skuQuantity: 10,
    unitPriceFen: 20,
    fixedRewardAmount: 0,
    sharingEnabled: true,
    sharingAutoFromOrder: true,
    sharingTotalQuantity: 1,
    sharingUnitReward: 0,
  })

  assert.deepEqual(pricing, {
    sharingTotalQuantity: 10,
    sharingUnitReward: 20,
    rewardAmount: 200,
  })
})

test('按件拼单手动覆盖数量和单价时，保留手工配置', () => {
  const pricing = resolveWorkOrderRulePricing({
    skuQuantity: 10,
    unitPriceFen: 20,
    fixedRewardAmount: 0,
    sharingEnabled: true,
    sharingAutoFromOrder: false,
    sharingTotalQuantity: 3,
    sharingUnitReward: 50,
  })

  assert.deepEqual(pricing, {
    sharingTotalQuantity: 3,
    sharingUnitReward: 50,
    rewardAmount: 150,
  })
})

test('模板同步价格按工单来源规格重新计算普通按件单', () => {
  const price = resolveWorkOrderTemplateSyncPrice({
    rule: buildProductRule({ unit_price_fen: 200 }),
    workOrder: buildWorkOrderRow({
      product_name: '指挥官秘钥15个',
      material_json: { source: { skuQuantity: 8 } },
    }),
  })

  assert.deepEqual(price, { rewardAmount: 1600 })
})

test('模板同步价格为拼单返回新的份额单价', () => {
  const price = resolveWorkOrderTemplateSyncPrice({
    rule: buildProductRule({
      unit_price_fen: 200,
      sharing_enabled: true,
      sharing_auto_from_order: true,
    }),
    workOrder: buildWorkOrderRow({
      product_name: '指挥官秘钥15个',
      sharing_enabled: true,
      sharing_total_quantity: 15,
    }),
  })

  assert.deepEqual(price, { rewardAmount: 3000, sharingUnitReward: 200 })
})

test('部分拼单同步后总报酬保留已加入份额的旧价格', () => {
  assert.equal(
    resolveOpenSharingSyncReward({
      totalQuantity: 10,
      joinedQuantity: 4,
      lockedShareReward: 4000,
      nextUnitReward: 1200,
    }),
    11_200,
  )
})

test('模板启用拼单但实际只有一份时生成普通工单', () => {
  assert.equal(resolveWorkOrderSharingEnabled(true, 1), false)
})

test('模板启用拼单且实际大于一份时生成拼单工单', () => {
  assert.equal(resolveWorkOrderSharingEnabled(true, 2), true)
  assert.equal(resolveWorkOrderSharingEnabled(false, 3), false)
})

test('拼单工单立即抢单承接全部剩余份数', () => {
  assert.equal(
    resolveWorkOrderShareJoinQuantity({ quantity: 0, remaining: 12, takeRemaining: true }),
    12,
  )
  assert.equal(
    resolveWorkOrderShareJoinQuantity({ quantity: 0, remaining: 0, takeRemaining: true }),
    0,
  )
})

test('拼单份数全部承接后不再显示在抢单大厅', () => {
  assert.equal(isWorkOrderSharingFilled(true, 15, 15), true)
  assert.equal(isWorkOrderSharingFilled(true, 15, 14), false)
  assert.equal(isWorkOrderSharingFilled(false, 15, 15), false)
})

function buildWorkOrderRow(overrides: Partial<WorkOrderRow> = {}): WorkOrderRow {
  return {
    id: 1,
    work_order_no: 'WO0001',
    order_id: 101,
    order_item_id: 201,
    task_id: null,
    platform_order_id: 'ORDER-001',
    product_name: '测试商品',
    category_id: null,
    status: 'pending_material',
    reward_amount: 2500,
    required_deposit_amount: 0,
    deposit_threshold_amount: 20000,
    assigned_worker_id: null,
    material_json: '{}',
    requirement_json: '{"fields":[]}',
    acceptance_json: '{}',
    problem_note: '',
    published_at: null,
    hall_queued_at: null,
    assigned_at: null,
    submitted_at: null,
    accepted_at: null,
    created_at: '2026-07-28T00:00:00.000Z',
    updated_at: '2026-07-28T00:00:00.000Z',
    ...overrides,
  }
}

function buildWorkOrderShareRow(overrides: Partial<WorkOrderShareRow> = {}): WorkOrderShareRow {
  return {
    id: 1,
    work_order_id: 1,
    worker_id: 1,
    quantity: 2,
    unit_reward: 700,
    share_reward: 1400,
    share_deposit: 200,
    status: 'joined',
    acceptance_json: {},
    draft_acceptance_json: {},
    submitted_at: null,
    accepted_at: null,
    created_at: '2026-08-18T09:09:08.000Z',
    updated_at: '2026-08-18T09:09:08.000Z',
    ...overrides,
  }
}

test('mapWorkOrderForWorker reflects the personal first-view state', () => {
  const workOrder = buildWorkOrderRow({ assigned_worker_id: 1 })
  const permissions = resolveWorkerPermissions(buildWorkerUserRow())
  assert.equal(mapWorkOrderForWorker(workOrder, permissions, null, '', null).isUnread, true)
  assert.equal(
    mapWorkOrderForWorker(workOrder, permissions, null, '', '2026-08-17T00:00:00.000Z').isUnread,
    false,
  )
  assert.equal(mapWorkOrderForWorker(workOrder, permissions).isUnread, undefined)
})

test('mapWorkOrderForWorker 使用个人拼单份数、金额、状态和接单时间', () => {
  const workOrder = buildWorkOrderRow({
    product_name: '指挥官秘钥15个',
    status: 'open',
    reward_amount: 10_500,
    sharing_enabled: true,
    sharing_total_quantity: 15,
    sharing_unit_reward: 700,
  })
  const share = buildWorkOrderShareRow()
  const mapped = mapWorkOrderForWorker(
    workOrder,
    resolveWorkerPermissions(buildWorkerUserRow()),
    share,
  )

  assert.equal(mapped.productName, '指挥官秘钥2个')
  assert.equal(mapped.rewardAmount, 1400)
  assert.equal(mapped.freezeDepositAmount, 200)
  assert.equal(mapped.status, 'in_progress')
  assert.equal(mapped.assignedAt, '2026-08-18T09:09:08.000Z')
})

test('打手拼单状态以个人份额为准，母工单终态优先', () => {
  assert.equal(resolveWorkerShareStatus('open', 'joined'), 'in_progress')
  assert.equal(resolveWorkerShareStatus('open', 'submitted'), 'pending_acceptance')
  assert.equal(resolveWorkerShareStatus('open', 'accepted'), 'accepted')
  assert.equal(resolveWorkerShareStatus('open', 'cancelled'), 'cancelled')
  assert.equal(resolveWorkerShareStatus('problem', 'joined'), 'problem')
})

test('打手订单状态筛选使用个人拼单份额状态', () => {
  const { joins, whereClause, params } = buildWorkOrderWhere({
    workerSharingId: 42,
    statuses: ['in_progress', 'pending_acceptance'],
  })

  assert.deepEqual(params, [42, ['in_progress', 'pending_acceptance']])
  assert.match(joins, /work_order_shares share_source/)
  assert.match(joins, /worker_share\.worker_id = \$1/)
  assert.match(whereClause, /WHEN 'joined' THEN 'in_progress'/)
  assert.match(whereClause, /WHEN 'submitted' THEN 'pending_acceptance'/)
  assert.match(whereClause, /worker_share\.status/)
  assert.match(whereClause, /= ANY\(\$2::text\[\]\)/)
})

test('好友赠送待打手提交资料筛选排除待抢单订单', () => {
  const { whereClause, params } = buildWorkOrderWhere({ giftPhase: 'material_required' })

  assert.deepEqual(params, ['material_required'])
  assert.match(whereClause, /wo\.acceptance_mode = 'friend_gift'/)
  assert.match(whereClause, /wo\.gift_phase = \$1/)
  assert.match(whereClause, /wo\.assigned_worker_id IS NOT NULL/)
  assert.match(whereClause, /wo\.status IN \('in_progress', 'problem'\)/)
})

test('好友赠送冷却中才允许客服手动结束冷却', () => {
  const cooling = mapWorkOrderAdmin(
    buildWorkOrderRow({
      status: 'in_progress',
      assigned_worker_id: 1,
      acceptance_mode: 'friend_gift',
      gift_phase: 'friend_countdown',
      gift_available_at: new Date(Date.now() + 60_000).toISOString(),
    }),
  )
  assert.equal(cooling.gift?.phase, 'friend_countdown')
  assert.equal(cooling.capabilities.canCompleteGiftCooldown, true)

  const completed = mapWorkOrderAdmin(
    buildWorkOrderRow({
      status: 'in_progress',
      assigned_worker_id: 1,
      acceptance_mode: 'friend_gift',
      gift_phase: 'friend_countdown',
      gift_available_at: new Date(Date.now() - 60_000).toISOString(),
    }),
  )
  assert.equal(completed.gift?.phase, 'gift_ready')
  assert.equal(completed.capabilities.canCompleteGiftCooldown, false)
})

test('后台拼单聚合状态同时收敛筛选语义和操作能力', () => {
  const waitingForClaim = mapWorkOrderAdmin(buildWorkOrderRow({ status: 'open' }))
  assert.equal(waitingForClaim.status, 'open')
  assert.equal(waitingForClaim.capabilities.canUpdateMaterial, true)

  const partial = mapWorkOrderAdmin(
    buildWorkOrderRow({
      status: 'open',
      sharing_enabled: true,
      sharing_total_quantity: 15,
      active_share_quantity: 3,
      pending_share_count: 1,
    }),
  )
  assert.equal(partial.status, 'in_progress')
  assert.equal(partial.rawStatus, 'open')
  assert.equal(partial.hallAvailable, true)
  assert.equal(partial.capabilities.canEdit, false)
  assert.equal(partial.capabilities.canConfigureSharing, false)
  assert.equal(partial.capabilities.canAssign, false)
  assert.equal(partial.capabilities.canUpdateMaterial, true)
  assert.equal(partial.capabilities.canCancelSharing, true)

  const filled = mapWorkOrderAdmin(
    buildWorkOrderRow({
      status: 'open',
      sharing_enabled: true,
      sharing_total_quantity: 15,
      active_share_quantity: 15,
      pending_share_count: 0,
    }),
  )
  assert.equal(filled.status, 'pending_acceptance')
  assert.equal(filled.hallAvailable, false)
  assert.equal(filled.capabilities.canAccept, true)
  assert.equal(filled.capabilities.canUnpublish, false)
  assert.equal(filled.capabilities.canCancelSharing, true)
})

test('已取消工单可重新启用，恢复未分配后可编辑和发布', () => {
  const cancelled = mapWorkOrderAdmin(buildWorkOrderRow({ status: 'cancelled' }))
  assert.equal(cancelled.capabilities.canReopen, true)
  assert.equal(cancelled.capabilities.canEdit, false)
  assert.equal(cancelled.capabilities.canPublish, false)

  const restored = mapWorkOrderAdmin(buildWorkOrderRow({ status: 'unassigned' }))
  assert.equal(restored.capabilities.canReopen, false)
  assert.equal(restored.capabilities.canEdit, true)
  assert.equal(restored.capabilities.canPublish, true)

  const cancelledSharing = mapWorkOrderAdmin(
    buildWorkOrderRow({
      status: 'cancelled',
      sharing_enabled: true,
      active_share_quantity: 1,
    }),
  )
  assert.equal(cancelledSharing.capabilities.canReopen, false)
})

test('拼单打手汇总展示当前参与者并合并同一打手的份数', () => {
  const workers = mapWorkOrderSharingWorkers([
    buildWorkOrderShareRow({ worker_id: 1, quantity: 2, worker_username: 'alpha' }),
    buildWorkOrderShareRow({ id: 2, worker_id: 1, quantity: 3, worker_username: 'alpha' }),
    buildWorkOrderShareRow({ id: 3, worker_id: 2, quantity: 1, worker_display_name: 'Beta' }),
    buildWorkOrderShareRow({ id: 4, worker_id: 3, quantity: 9, status: 'cancelled' }),
  ])

  assert.deepEqual(workers, [
    { workerId: 1, username: 'alpha', displayName: 'alpha', quantity: 5 },
    { workerId: 2, username: '', displayName: 'Beta', quantity: 1 },
  ])
})

test('拼单份额撤单只允许未验收份额并让母工单回到大厅状态', () => {
  assert.equal(resolveWorkOrderShareCancellationStatus('open', 'joined'), 'open')
  assert.equal(resolveWorkOrderShareCancellationStatus('open', 'submitted'), 'open')
  assert.equal(resolveWorkOrderShareCancellationStatus('pending_acceptance', 'submitted'), 'open')
  assert.equal(resolveWorkOrderShareCancellationStatus('pending_acceptance', 'accepted'), null)
  assert.equal(resolveWorkOrderShareCancellationStatus('accepted', 'submitted'), null)
  assert.equal(resolveWorkOrderShareCancellationStatus('open', 'cancelled'), null)
})

test('拼单母单撤单区分退回大厅和取消整单的验收边界', () => {
  assert.deepEqual(
    resolveWorkOrderSharingCancellationPlan(
      'pending_acceptance',
      ['submitted', 'accepted'],
      'return_to_hall',
    ),
    {
      nextOrderStatus: 'open',
      cancellableShareCount: 1,
      acceptedShareCount: 1,
      failureReason: null,
    },
  )
  assert.equal(
    resolveWorkOrderSharingCancellationPlan(
      'pending_acceptance',
      ['submitted', 'accepted'],
      'cancel_order',
    ).failureReason,
    'accepted_shares_present',
  )
  assert.deepEqual(
    resolveWorkOrderSharingCancellationPlan('open', ['joined', 'submitted'], 'cancel_order'),
    {
      nextOrderStatus: 'cancelled',
      cancellableShareCount: 2,
      acceptedShareCount: 0,
      failureReason: null,
    },
  )
  assert.equal(
    resolveWorkOrderSharingCancellationPlan('accepted', ['submitted'], 'return_to_hall')
      .failureReason,
    'work_order_not_cancellable',
  )
})

test('问题单退回打手按标记前状态恢复', () => {
  assert.equal(resolveProblemReturnToWorkerStatus('pending_acceptance'), 'pending_acceptance')
  assert.equal(resolveProblemReturnToWorkerStatus('open'), 'open')
  assert.equal(resolveProblemReturnToWorkerStatus('in_progress'), 'in_progress')
  assert.equal(resolveProblemReturnToWorkerStatus(''), 'in_progress')
})

test('后台更新资料时普通接单可以修改接单价格', () => {
  assert.equal(
    resolveAdminMaterialRewardAmount({
      currentRewardAmount: 1280,
      requestedRewardAmount: 15.5,
      sharingEnabled: false,
      activeShareQuantity: 0,
    }),
    1550,
  )
})

test('后台更新资料未提交价格时保留原接单价格', () => {
  assert.equal(
    resolveAdminMaterialRewardAmount({
      currentRewardAmount: 1280,
      requestedRewardAmount: undefined,
      sharingEnabled: false,
      activeShareQuantity: 0,
    }),
    1280,
  )
})

test('后台更新资料禁止修改已有参与者的拼单价格', () => {
  assert.throws(
    () =>
      resolveAdminMaterialRewardAmount({
        currentRewardAmount: 3840,
        requestedRewardAmount: 15.5,
        sharingEnabled: true,
        activeShareQuantity: 3,
      }),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 409 &&
        (error as { errorCode?: string }).errorCode ===
          'work_order_material_reward_sharing_invalid',
      ),
  )
})

test('resolveCollectSubmitTargetWorkOrder returns the only pending work order when no id is provided', () => {
  const workOrder = buildWorkOrderRow()
  const selected = resolveCollectSubmitTargetWorkOrder('ORDER-001', [workOrder], '')
  assert.equal(selected.id, workOrder.id)
})

test('resolveCollectSubmitTargetWorkOrder requires explicit work order id when multiple orders are pending', () => {
  const workOrders = [
    buildWorkOrderRow({ id: 1, work_order_no: 'WO0001' }),
    buildWorkOrderRow({ id: 2, work_order_no: 'WO0002', order_item_id: 202 }),
  ]

  assert.throws(
    () => resolveCollectSubmitTargetWorkOrder('ORDER-001', workOrders, ''),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 409 &&
        (error as { errorCode?: string }).errorCode === 'collect_work_order_required',
      ),
  )
})

test('resolveCollectSubmitTargetWorkOrder returns the matching work order when workOrderId is provided', () => {
  const workOrders = [
    buildWorkOrderRow({ id: 1, work_order_no: 'WO0001' }),
    buildWorkOrderRow({ id: 2, work_order_no: 'WO0002', order_item_id: 202 }),
  ]

  const selected = resolveCollectSubmitTargetWorkOrder('ORDER-001', workOrders, '2')
  assert.equal(selected.id, 2)
})

test('resolveCollectSubmitTargetWorkOrder rejects unknown workOrderId', () => {
  const workOrders = [buildWorkOrderRow({ id: 1, work_order_no: 'WO0001' })]

  assert.throws(
    () => resolveCollectSubmitTargetWorkOrder('ORDER-001', workOrders, 999),
    (error: unknown) =>
      Boolean(
        error &&
        typeof error === 'object' &&
        (error as { statusCode?: number }).statusCode === 404 &&
        (error as { errorCode?: string }).errorCode === 'collect_work_order_not_found',
      ),
  )
})

test('资金流水映射展示关联的平台订单号', () => {
  const ledger = {
    id: 1,
    worker_id: 1,
    ledger_type: 'reward_settlement',
    amount: 2500,
    balance_after: 2500,
    frozen_after: 0,
    related_work_order_id: 44,
    related_platform_order_id: '2623301845665410',
    audit_status: 'approved',
    note: '验收通过结算报酬',
    payload_json: {},
    created_at: '2026-08-21T00:00:00.000Z',
  } satisfies WorkerWalletLedgerRow

  assert.equal(mapWalletLedger(ledger)?.relatedPlatformOrderId, '2623301845665410')
})
