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

import {
  buildFileUrl,
  normalizeStoredFileUrl,
  refreshStoredFileUrl,
  verifyFileAccessSignature,
} from './file-storage-service.js'

const NOW_SECONDS = 1_800_000_000
const OBJECT_KEY = 'worker-acceptance/2026/07/26/example.jpg'

test('file access URL carries a valid short-lived signature', () => {
  const url = buildFileUrl(OBJECT_KEY, NOW_SECONDS)
  const parsed = new URL(url, 'http://localhost')

  assert.equal(parsed.searchParams.get('key'), OBJECT_KEY)
  assert.doesNotThrow(() =>
    verifyFileAccessSignature(
      OBJECT_KEY,
      parsed.searchParams.get('expires'),
      parsed.searchParams.get('signature'),
      NOW_SECONDS + 899,
    ),
  )
})

test('file access URL rejects expired and tampered signatures', () => {
  const parsed = new URL(buildFileUrl(OBJECT_KEY, NOW_SECONDS), 'http://localhost')
  const expires = parsed.searchParams.get('expires')
  const signature = parsed.searchParams.get('signature')

  assert.throws(() => verifyFileAccessSignature(OBJECT_KEY, expires, signature, NOW_SECONDS + 901))
  assert.throws(() =>
    verifyFileAccessSignature(`${OBJECT_KEY}.changed`, expires, signature, NOW_SECONDS),
  )
})

test('stored file URL drops signatures and refreshes them for responses', () => {
  const signedUrl = buildFileUrl(OBJECT_KEY, NOW_SECONDS)
  const storedUrl = normalizeStoredFileUrl(signedUrl)
  const refreshedUrl = refreshStoredFileUrl(storedUrl)

  assert.equal(storedUrl, `/api/v1/files/object?key=${encodeURIComponent(OBJECT_KEY)}`)
  assert.match(refreshedUrl, /[?&]expires=\d+/)
  assert.match(refreshedUrl, /[?&]signature=/)
  assert.equal(
    refreshStoredFileUrl('https://example.com/image.jpg'),
    'https://example.com/image.jpg',
  )
})
