import { describe, it, expect } from 'vitest'
import { decodeJwtPayload } from './jwt'

describe('jwt utilities', () => {
    describe('decodeJwtPayload', () => {
        it('should decode a valid JWT payload', () => {
            // JWT with payload: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
            const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'

            const result = decodeJwtPayload<{ sub: string; name: string; iat: number }>(token)

            expect(result).not.toBeNull()
            expect(result?.sub).toBe('1234567890')
            expect(result?.name).toBe('John Doe')
            expect(result?.iat).toBe(1516239022)
        })

        it('should return null for undefined token', () => {
            const result = decodeJwtPayload(undefined)
            expect(result).toBeNull()
        })

        it('should return null for empty token', () => {
            const result = decodeJwtPayload('')
            expect(result).toBeNull()
        })

        it('should return null for invalid token format', () => {
            const result = decodeJwtPayload('invalid-token-without-dots')
            expect(result).toBeNull()
        })

        it('should return null for malformed base64', () => {
            const result = decodeJwtPayload('header.!!!invalid-base64!!!.signature')
            expect(result).toBeNull()
        })

        it('should handle URL-safe base64 characters', () => {
            // Token with URL-safe base64 (- and _)
            const token = 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidGVzdC11c2VyLWlkIn0.sig'
            const result = decodeJwtPayload<{ user_id: string }>(token)

            expect(result).not.toBeNull()
            expect(result?.user_id).toBe('test-user-id')
        })
    })
})
