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

import {
  mapKuaishouEticketDetailResult,
  normalizeKuaishouEticketApiResult,
  resolveKuaishouEticketConsumePayload,
} from './consume-service.js'

test('normalizeKuaishouEticketApiResult recognizes already consumed response', () => {
  const result = normalizeKuaishouEticketApiResult({
    result: 21,
    error_msg: '券码已核销无法再次核销，请核实后重试',
    requestId: 'abc',
  })

  assert.equal(result.ok, false)
  assert.equal(result.result, 21)
  assert.equal(result.errorMessage, '券码已核销无法再次核销，请核实后重试')
  assert.equal(result.requestId, 'abc')
})

test('mapKuaishouEticketDetailResult maps detail payload fields', () => {
  const result = mapKuaishouEticketDetailResult({
    result: 1,
    error_msg: '成功',
    data: {
      eTicket: {
        eTicketId: 'F2E886B6CBF8E5F5',
        oid: '2612200246413561',
        formToken: '1777716306154',
        leftCount: 1,
        totalCount: 1,
        status: 'CONSUME_ORDER_CREATED',
      },
      goods: {
        itemTitle: '测试链接五排',
        skuDesc: '测试1',
      },
    },
  }, {
    baseUrl: 'https://s.kwaixiaodian.com',
    eTicketId: 'F2E886B6CBF8E5F5',
  })

  assert.equal(result.ok, true)
  assert.equal(result.detail?.oid, '2612200246413561')
  assert.equal(result.detail?.formToken, '1777716306154')
  assert.equal(result.detail?.leftCount, 1)
  assert.equal(result.goods?.itemTitle, '测试链接五排')
})

test('resolveKuaishouEticketConsumePayload falls back to detail result', () => {
  const payload = resolveKuaishouEticketConsumePayload({
    eTicketId: 'F2E886B6CBF8E5F5',
  }, {
    detail: {
      eTicketId: 'F2E886B6CBF8E5F5',
      oid: '2612200246413561',
      formToken: '1777716306154',
      leftCount: 2,
    },
  })

  assert.deepEqual(payload, {
    eTicketId: 'F2E886B6CBF8E5F5',
    num: 2,
    storeId: '0',
    oid: '2612200246413561',
    formToken: '1777716306154',
  })
})
