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

import { runtimeConfig } from '../../../../config/runtime.js'
import {
  deliverAgisoXianyuMessageForTaskWithDeps,
  normalizeAgisoMessageTemplate,
  renderAgisoAutoDeliveryMessage,
} from './message-service.js'

test('deliverAgisoXianyuMessageForTaskWithDeps skips duplicate successful claim message by order scope', async () => {
  const originalMessaging = runtimeConfig.platforms.agiso.messaging
  const originalAppSecret = runtimeConfig.platforms.agiso.appSecret

  runtimeConfig.platforms.agiso.messaging = {
    ...originalMessaging,
    enabled: true,
    sendMessageEndpoint: 'https://example.com/send',
    apiVersion: '1',
    accessToken: 'access-token',
  }
  runtimeConfig.platforms.agiso.appSecret = 'app-secret'

  const calls = {
    find: [],
    create: 0,
    fetch: 0,
  }

  try {
    const result = await deliverAgisoXianyuMessageForTaskWithDeps({
      order: {
        id: 15,
        platform: 'xianyu',
        shop_id: '2209880145223',
        platform_order_id: '4502280133178028841',
      },
      task: {
        id: 36,
        task_no: 'DT7af76e9b2438',
      },
      channel: 'agiso_im',
      messageContent: '测试消息',
      claimUrl: 'https://221329.cc.cd/#/claim/same-token',
    }, {
      findLatestSuccessfulMessageDelivery: async (input) => {
        calls.find.push(input)
        return { id: 16, task_id: null }
      },
      createMessageDelivery: async () => {
        calls.create += 1
        return { id: 999 }
      },
      fetch: async () => {
        calls.fetch += 1
        return { status: 200, text: async () => '{}' }
      },
    })

    assert.deepEqual(calls.find, [
      {
        provider: 'agiso',
        platform: 'xianyu',
        shopId: '2209880145223',
        platformOrderId: '4502280133178028841',
        channel: 'agiso_im',
        claimUrl: 'https://221329.cc.cd/#/claim/same-token',
      },
    ])
    assert.equal(calls.create, 0)
    assert.equal(calls.fetch, 0)
    assert.equal(result.sent, false)
    assert.equal(result.skipped, true)
    assert.equal(result.reason, 'already_sent')
    assert.equal(result.deliveryId, 16)
  } finally {
    runtimeConfig.platforms.agiso.messaging = originalMessaging
    runtimeConfig.platforms.agiso.appSecret = originalAppSecret
  }
})

test('normalizeAgisoMessageTemplate converts escaped newline sequences into real line breaks', () => {
  assert.equal(
    normalizeAgisoMessageTemplate('第一行\\n第二行\\r\\n第三行'),
    '第一行\n第二行\n第三行',
  )
})

test('renderAgisoAutoDeliveryMessage supports escaped newlines in configured template', () => {
  const message = renderAgisoAutoDeliveryMessage({
    order: {
      platform_order_id: '4502280133178028841',
      shop_id: '2209880145223',
      shop_name: '大锤号商',
    },
    task: {
      task_no: 'DT7af76e9b2438',
    },
    template: '订单 {platformOrderId}\\n结果：{resultMessage}',
  })

  assert.equal(message, '订单 4502280133178028841\n结果：自动发货成功')
})
