import Fastify from 'fastify'
import privyPlugin, {getAuthorizationSignature} from '../../src/plugins/custom/privy.js'
import assert from 'node:assert'
import test from 'node:test'

// Set environment variables needed for the test
process.env.PRIVY_APP_ID = 'cm4db8x9t000ccn87pctvcg9j'
process.env.PRIVY_APP_SECRET = 'test-secret'
process.env.PRIVY_AUTHORIZATION_KEY = 'wallet-auth:MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgqOBE+hZld+PCaj051uOl0XpEwe3tKBC5tsYsKdnPymGhRANCAAQ2HyYUbLRcfj9obpViwjYU/S7FdNUehkcfjYdd+R2gH/1q0ZJx7mOF1zpiEbbBNRLuXzP0NPN6nonkI8umzLXZ'

test('getAuthorizationSignature generates valid signatures', async () => {
  const url = 'https://api.privy.io/v1/wallets'
  const body = { chain_type: 'ethereum' }
  
  const signature = getAuthorizationSignature({ url, body })
  
  // Basic validation - check if it's a non-empty string that looks like a base64 value
  assert.ok(signature && typeof signature === 'string', 'Signature should be a string')
  assert.ok(signature.length > 0, 'Signature should not be empty')
  
  // Check if signature matches base64 pattern
  const base64Regex = /^[A-Za-z0-9+/]+={0,2}$/
  assert.ok(base64Regex.test(signature), 'Signature should be a valid base64 string')
})

test('privy plugin decorates request with signPrivyMessage', async (t) => {
  const app = Fastify()
  
  t.after(() => {
    app.close()
  })
  
  await app.register(privyPlugin)
  
  app.get('/', (request) => {
    return { 
      decorated: {
        signPrivyMessage: !!request.signPrivyMessage,
      }
    }
  })
  
  const result = await app.inject({
    method: 'GET',
    url: '/'
  }).then(r => r.json())
  
  assert.equal(result.decorated.signPrivyMessage, true, 'Request should be decorated with signPrivyMessage method')
})
