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

import { mergeWebhookOrderState } from './order-service.js'

test('mergeWebhookOrderState keeps paid state when a late trade_create webhook arrives', () => {
  const merged = mergeWebhookOrderState(
    {
      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('mergeWebhookOrderState upgrades unpaid orders when payment webhook arrives later', () => {
  const merged = mergeWebhookOrderState(
    {
      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('mergeWebhookOrderState preserves refunded status over older paid webhook', () => {
  const merged = mergeWebhookOrderState(
    {
      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')
})
