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

import type { WorkOrderRow } from '../../repositories/worker-platform/index.js'
import { resolveCollectSubmitTargetWorkOrder } from './index.js'

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,
    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,
  }
}

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',
      ),
  )
})
