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

import { sendWpushNotification } from './wpush-service.js'

test('sendWpushNotification sends POST json payload', async () => {
  const captured = {
    method: '',
    contentType: '',
    body: '',
  }

  const server = http.createServer((req, res) => {
    captured.method = String(req.method || '')
    captured.contentType = String(req.headers['content-type'] || '')

    const chunks: Buffer[] = []
    req.on('data', (chunk) => {
      chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
    })
    req.on('end', () => {
      captured.body = Buffer.concat(chunks).toString('utf8')
      res.writeHead(200, { 'content-type': 'application/json' })
      res.end(JSON.stringify({ code: 0, message: 'ok' }))
    })
  })

  await new Promise<void>((resolve) => {
    server.listen(0, '127.0.0.1', () => resolve())
  })

  try {
    const address = server.address()
    assert.ok(address && typeof address === 'object')

    const result = await sendWpushNotification({
      endpoint: `http://127.0.0.1:${address.port}/send`,
      recipient: {
        apiKey: 'test-key-1',
      },
      title: '测试标题',
      body: '测试内容',
    })

    assert.equal(result.ok, true)
    assert.equal(captured.method, 'POST')
    assert.equal(captured.contentType, 'application/json')
    assert.deepEqual(JSON.parse(captured.body), {
      apikey: 'test-key-1',
      title: '测试标题',
      content: '测试内容',
    })
  } finally {
    await new Promise<void>((resolve, reject) => {
      server.close((error) => {
        if (error) {
          reject(error)
          return
        }
        resolve()
      })
    })
  }
})

test('sendWpushNotification rejects missing api key', async () => {
  await assert.rejects(
    () =>
      sendWpushNotification({
        recipient: {},
        title: '测试标题',
        body: '测试内容',
      }),
    (error: any) => {
      assert.equal(error?.errorCode, 'wpush_api_key_required')
      return true
    },
  )
})
