import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import test from 'node:test'

import { ObjectStorage } from './object-storage.js'

test('S3 签名使用配置的对象存储 region', async () => {
  const authorizationHeaders: string[] = []
  const server = createServer((request, response) => {
    const authorization = request.headers.authorization
    if (authorization) authorizationHeaders.push(authorization)
    response.statusCode = 200
    response.end()
  })
  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 storage = new ObjectStorage({
      endpoint: `http://127.0.0.1:${address.port}`,
      bucket: 'order-site',
      accessKeyId: 'test-access-key',
      secretAccessKey: 'test-secret-key',
      region: 'oss-cn-hangzhou',
    })

    await storage.putObject({
      key: 'test/example.jpg',
      content: Buffer.from('test'),
      contentType: 'image/jpeg',
    })

    assert.ok(authorizationHeaders.length >= 2)
    assert.match(
      authorizationHeaders[0] || '',
      /Credential=test-access-key\/\d{8}\/oss-cn-hangzhou\//,
    )
    assert.match(
      authorizationHeaders.at(-1) || '',
      /Credential=test-access-key\/\d{8}\/oss-cn-hangzhou\//,
    )
  } finally {
    await new Promise<void>((resolve, reject) =>
      server.close((error) => (error ? reject(error) : resolve())),
    )
  }
})
