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

import { listOrdersWithExecutor, type OrderQueryExecutor } from './order-repo.js'

test('订单列表综合筛选下推到总数和分页查询', async () => {
  const calls: Array<{ sql: string; params: unknown[] }> = []
  const executor = createExecutor(calls, 3)

  const result = await listOrdersWithExecutor(executor, {
    page: 2,
    pageSize: 10,
    keyword: '皮肤店',
    provider: '91kaquan',
    executorKey: 'kuaishou_ct_assisted',
    payStatus: 'paid',
    taskStatus: 'manual_review',
    dateFrom: '2026-09-01T00:00:00.000Z',
    dateTo: '2026-09-02T23:59:59.999Z',
  })

  assert.equal(result.total, 3)
  assert.equal(calls.length, 2)
  assert.match(calls[0]?.sql || '', /o\.platform_order_id.*ILIKE \$1/s)
  assert.match(calls[0]?.sql || '', /oi\.sku_code.*oi\.sku_name.*ILIKE \$1/s)
  assert.match(calls[0]?.sql || '', /kuaishouSendCode'.*itemTitle.*kuaishouSendCode'.*skuNick/s)
  assert.match(calls[0]?.sql || '', /o\.provider = \$2/)
  assert.match(calls[0]?.sql || '', /o\.pay_status = \$3/)
  assert.match(calls[0]?.sql || '', /ft\.task_status = \$4/)
  assert.match(calls[0]?.sql || '', /ft\.executor_key = \$5/)
  assert.match(calls[0]?.sql || '', /o\.created_at >= \$6/)
  assert.match(calls[0]?.sql || '', /o\.created_at <= \$7/)
  assert.deepEqual(calls[0]?.params, [
    '%皮肤店%',
    '91kaquan',
    'paid',
    'manual_review',
    'kuaishou_ct_assisted',
    '2026-09-01T00:00:00.000Z',
    '2026-09-02T23:59:59.999Z',
  ])
  assert.match(calls[1]?.sql || '', /LIMIT \$8 OFFSET \$9/)
  assert.deepEqual(calls[1]?.params, [...(calls[0]?.params || []), 10, 10])
})

test('订单列表保留订单号和精确 SKU 旧筛选参数兼容', async () => {
  const calls: Array<{ sql: string; params: unknown[] }> = []

  await listOrdersWithExecutor(createExecutor(calls, 0), {
    platformOrderId: '26245',
    skuCode: 'SKU-1',
  })

  assert.match(calls[0]?.sql || '', /o\.platform_order_id ILIKE \$1/)
  assert.match(calls[0]?.sql || '', /oi\.sku_code = \$2/)
  assert.deepEqual(calls[0]?.params, ['%26245%', 'SKU-1'])
})

function createExecutor(
  calls: Array<{ sql: string; params: unknown[] }>,
  total: number,
): OrderQueryExecutor {
  return (async (sql: string, params: unknown[] = []) => {
    calls.push({ sql, params: [...params] })
    return {
      command: 'SELECT',
      rowCount: calls.length === 1 ? 1 : 0,
      oid: 0,
      fields: [],
      rows: calls.length === 1 ? [{ total }] : [],
    }
  }) as OrderQueryExecutor
}
