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

import {
  ORDER_FULFILLMENT_BLOCK_REASONS,
  resolveOrderFulfillmentReadiness,
} from './order-fulfillment-readiness-service.js'
import type { KuaishouIndustryVoucherRow } from '../../types/repository/rows.js'

test('resolveOrderFulfillmentReadiness 无电子凭证时允许继续履约', async () => {
  const readiness = await resolveOrderFulfillmentReadiness(
    { platform_order_id: '2614900602069169' },
    {
      listKuaishouIndustryVouchersByOid: async () => [],
    },
  )

  assert.deepEqual(readiness, {
    allowed: true,
    voucherCount: 0,
    reason: '',
    blockReason: '',
  })
})

test('resolveOrderFulfillmentReadiness 电子凭证发码成功时允许继续履约', async () => {
  const readiness = await resolveOrderFulfillmentReadiness(
    { platform_order_id: '2614900602069169' },
    {
      listKuaishouIndustryVouchersByOid: async () => [
        createVoucher({ send_callback_status: 'success' }),
      ],
    },
  )

  assert.deepEqual(readiness, {
    allowed: true,
    voucherCount: 1,
    reason: '',
    blockReason: '',
  })
})

test('resolveOrderFulfillmentReadiness 电子凭证发码未确认时阻止履约', async () => {
  const readiness = await resolveOrderFulfillmentReadiness(
    { platform_order_id: '2614900602069169' },
    {
      listKuaishouIndustryVouchersByOid: async () => [
        createVoucher({
          send_callback_status: 'pending',
          send_callback_last_error: '回调等待中',
        }),
      ],
    },
  )

  assert.deepEqual(readiness, {
    allowed: false,
    voucherCount: 1,
    reason: '回调等待中',
    blockReason: ORDER_FULFILLMENT_BLOCK_REASONS.KUAISHOU_INDUSTRY_SEND_CALLBACK_UNCONFIRMED,
  })
})

function createVoucher(
  patch: Partial<KuaishouIndustryVoucherRow> = {},
): KuaishouIndustryVoucherRow {
  return {
    id: 1,
    voucher_code: 'ETICKET-1',
    oid: '2614900602069169',
    order_id: null,
    task_id: null,
    unit_index: 1,
    seller_id: '',
    token: '',
    status: 'UNUSED',
    valid_start_time: 0,
    valid_end_time: 0,
    consume_serial_num: '',
    consume_details_json: [],
    consumed_at: null,
    destroyed_at: null,
    send_callback_status: 'success',
    send_callback_attempt_count: 0,
    send_callback_last_error: '',
    send_callback_response_json: {},
    send_callback_sent_at: null,
    raw_payload_json: {},
    created_at: '2026-07-08T00:00:00.000Z',
    updated_at: '2026-07-08T00:00:00.000Z',
    ...patch,
  }
}
