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

import {
  resolveSendCallbackGoodsValuePlan,
  resolveSendCallbackPreferredTotalGoodsValue,
} from './send-code-service.js'

test('resolveSendCallbackPreferredTotalGoodsValue converts 91 maxAmount yuan to fen', () => {
  const total = resolveSendCallbackPreferredTotalGoodsValue({
    raw_payload_json: JSON.stringify({
      body: {
        maxAmount: '0.01',
      },
    }),
    total_amount: 100,
  } as any)

  assert.equal(total, 1)
})

test('resolveSendCallbackPreferredTotalGoodsValue falls back to order total amount', () => {
  const total = resolveSendCallbackPreferredTotalGoodsValue({
    raw_payload_json: '{}',
    total_amount: 66,
  } as any)

  assert.equal(total, 66)
})

test('resolveSendCallbackGoodsValuePlan prefers 91 amount over ext payment', () => {
  const plan = resolveSendCallbackGoodsValuePlan([{}], '{"payment":100,"platformBearAmount":0}', 1)

  assert.deepEqual(plan.goodsValues, [1])
  assert.equal(plan.totalGoodsValue, 1)
  assert.equal(plan.source, 'preferred')
})

test('resolveSendCallbackGoodsValuePlan splits preferred amount and keeps sum equal to total', () => {
  const plan = resolveSendCallbackGoodsValuePlan([{}, {}, {}], '{"payment":999}', 100)

  assert.deepEqual(plan.goodsValues, [33, 33, 34])
  assert.equal(plan.totalGoodsValue, 100)
  assert.equal(plan.source, 'preferred')
})

test('resolveSendCallbackGoodsValuePlan uses ext payment for a single voucher', () => {
  const plan = resolveSendCallbackGoodsValuePlan([{}], '{"payment":1,"platformBearAmount":0}')

  assert.deepEqual(plan.goodsValues, [1])
  assert.equal(plan.totalGoodsValue, 1)
})

test('resolveSendCallbackGoodsValuePlan splits ext payment and keeps sum equal to total', () => {
  const plan = resolveSendCallbackGoodsValuePlan([{}, {}, {}], '{"payment":100}')

  assert.deepEqual(plan.goodsValues, [33, 33, 34])
  assert.equal(plan.totalGoodsValue, 100)
})

test('resolveSendCallbackGoodsValuePlan falls back to one weight per voucher', () => {
  const plan = resolveSendCallbackGoodsValuePlan([{}, {}], '')

  assert.deepEqual(plan.goodsValues, [1, 1])
  assert.equal(plan.totalGoodsValue, 2)
})
