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

import { isOrderItemConfiguredForFulfillment, mergeSourceOrderState } from './order-service.js'
import type { OrderItemRow } from '../../types/repository/rows.js'

function buildOrderItem(snapshot: OrderItemRow['item_snapshot_json']): OrderItemRow {
  return {
    id: 1,
    order_id: 1,
    sku_code: 'TEST-SKU',
    sku_name: '测试商品',
    quantity: 1,
    spec_json: '{}',
    item_snapshot_json: snapshot,
  }
}

test('isOrderItemConfiguredForFulfillment accepts PostgreSQL JSONB object results', () => {
  assert.equal(isOrderItemConfiguredForFulfillment(buildOrderItem({ isConfigured: true })), true)
})

test('isOrderItemConfiguredForFulfillment accepts serialized snapshots', () => {
  assert.equal(isOrderItemConfiguredForFulfillment(buildOrderItem('{"isConfigured":true}')), true)
})

test('isOrderItemConfiguredForFulfillment rejects unconfigured or malformed snapshots', () => {
  assert.equal(isOrderItemConfiguredForFulfillment(buildOrderItem({})), false)
  assert.equal(isOrderItemConfiguredForFulfillment(buildOrderItem('{invalid')), false)
})

test('mergeSourceOrderState keeps paid state when a late created source event arrives', () => {
  const merged = mergeSourceOrderState(
    {
      order_status: 'paid',
      pay_status: 'paid',
      paid_at: '2026-04-14T10:06:10.000Z',
    },
    {
      orderStatus: 'created',
      payStatus: 'unpaid',
      paidAt: null,
    },
  )

  assert.equal(merged.orderStatus, 'paid')
  assert.equal(merged.payStatus, 'paid')
  assert.equal(merged.paidAt, '2026-04-14T10:06:10.000Z')
})

test('mergeSourceOrderState upgrades unpaid orders when payment source event arrives later', () => {
  const merged = mergeSourceOrderState(
    {
      order_status: 'created',
      pay_status: 'unpaid',
      paid_at: null,
    },
    {
      orderStatus: 'paid',
      payStatus: 'paid',
      paidAt: '2026-04-14T10:06:12.000Z',
    },
  )

  assert.equal(merged.orderStatus, 'paid')
  assert.equal(merged.payStatus, 'paid')
  assert.equal(merged.paidAt, '2026-04-14T10:06:12.000Z')
})

test('mergeSourceOrderState preserves refunded status over older paid source event', () => {
  const merged = mergeSourceOrderState(
    {
      order_status: 'refunded',
      pay_status: 'refunded',
      paid_at: '2026-04-14T10:06:10.000Z',
    },
    {
      orderStatus: 'paid',
      payStatus: 'paid',
      paidAt: '2026-04-14T10:06:09.000Z',
    },
  )

  assert.equal(merged.orderStatus, 'refunded')
  assert.equal(merged.payStatus, 'refunded')
  assert.equal(merged.paidAt, '2026-04-14T10:06:09.000Z')
})
