const test = require('node:test')
const assert = require('node:assert')
const { enhanceFirebaseAuthUserMessage } = require('../src/lib/errors')

test('enhanceFirebaseAuthUserMessage replaces long Firebase expired text with a short login hint', () => {
  const raw =
    'Firebase ID token has expired. Get a fresh ID token from your client app and try again (auth/id-token-expired).'
  const out = enhanceFirebaseAuthUserMessage(raw, {})
  assert.strictEqual(
    out,
    'Your authentication token has expired. Please run "bild login" again.'
  )
})

test('enhanceFirebaseAuthUserMessage uses error code when message is generic', () => {
  const out = enhanceFirebaseAuthUserMessage('Something failed', { code: 'auth/id-token-expired' })
  assert.strictEqual(
    out,
    'Your authentication token has expired. Please run "bild login" again.'
  )
})

test('enhanceFirebaseAuthUserMessage replaces invalid ID token decode text without naming Firebase', () => {
  const raw =
    'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
  assert.strictEqual(
    enhanceFirebaseAuthUserMessage(raw, {}),
    'Could not decode the ID token. Make sure you passed the complete JWT string from your sign-in flow.'
  )
})

test('enhanceFirebaseAuthUserMessage leaves unrelated errors unchanged', () => {
  const raw = 'Template not found'
  assert.strictEqual(enhanceFirebaseAuthUserMessage(raw, {}), raw)
})

test('enhanceFirebaseAuthUserMessage does not double-append when hint already present', () => {
  const raw = 'Expired. Run "bild login" to refresh your session.'
  assert.strictEqual(enhanceFirebaseAuthUserMessage(raw, { code: 'auth/id-token-expired' }), raw)
})
