const test = require('node:test')
const assert = require('node:assert')
const {
  buildStorageObjectRelativePath,
  buildFirebaseStorageDownloadUrl,
  projectIdFromFirebaseIdToken,
  defaultGcsBucketForFirebaseProjectId,
  pickStorageBucketFromCmsConfig,
} = require('../src/lib/firebase-storage-media')

test('buildStorageObjectRelativePath: no tenant', () => {
  assert.strictEqual(buildStorageObjectRelativePath(null, 'app-1', 'x.png'), 'app-1/x.png')
})

test('buildStorageObjectRelativePath: with tenant', () => {
  assert.strictEqual(buildStorageObjectRelativePath('t1', 'app-1', 'x.png'), 't1/app-1/x.png')
})

test('buildFirebaseStorageDownloadUrl: encodes nested object path + token', () => {
  const url = buildFirebaseStorageDownloadUrl('my-bucket.appspot.com', 't1/app-1/x.png', 'tok_abc')
  assert.ok(url.startsWith('https://firebasestorage.googleapis.com/v0/b/'))
  assert.ok(url.includes('/o/t1%2Fapp-1%2Fx.png'))
  assert.ok(url.includes('alt=media'))
  assert.ok(url.includes('token=tok_abc'))
})

test('projectIdFromFirebaseIdToken + default bucket mapping', () => {
  // payload: { aud: "pid", iss: "https://securetoken.google.com/pid" } (unsigned, but we only decode)
  const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')
  const payload = Buffer.from(
    JSON.stringify({ aud: 'demo-proj', iss: 'https://securetoken.google.com/demo-proj' })
  ).toString('base64url')
  const jwt = `${header}.${payload}.sig`
  assert.strictEqual(projectIdFromFirebaseIdToken(jwt), 'demo-proj')
  assert.strictEqual(defaultGcsBucketForFirebaseProjectId('demo-proj'), 'demo-proj.appspot.com')
})

test('pickStorageBucketFromCmsConfig: common shapes', () => {
  assert.strictEqual(
    pickStorageBucketFromCmsConfig({ storageBucket: 'b1' }),
    'b1'
  )
  assert.strictEqual(
    pickStorageBucketFromCmsConfig({ firebase: { storageBucket: 'b2' } }),
    'b2'
  )
})
