/**
 * Contract Tests for mizan JWT Server Functions
 *
 * Validates that the backend schema exports the expected JWT functions.
 * These tests catch frontend/backend contract mismatches early.
 */

import mizanSchema from '@/api/generated.mizan.schema.json'

type mizanFunction = {
    name: string
    camelName: string
    hasInput: boolean
    inputType: string | null
    outputType: string
    transport: string
}

function getFunctions(): mizanFunction[] {
    return (mizanSchema as any)['x-mizan-functions'] ?? []
}

function findFunction(name: string): mizanFunction | undefined {
    return getFunctions().find(fn => fn.name === name)
}

describe('JWT Server Functions Contract', () => {
    describe('jwt_obtain', () => {
        it('should be registered as a server function', () => {
            const fn = findFunction('jwt_obtain')
            expect(fn).toBeDefined()
            expect(fn?.transport).toBe('http')
        })

        it('should have no input (session-based)', () => {
            const fn = findFunction('jwt_obtain')
            expect(fn?.hasInput).toBe(false)
        })

        it('should return token pair with expected fields', () => {
            const schemas = (mizanSchema as any).components?.schemas
            const output = schemas?.jwtObtainOutput

            expect(output).toBeDefined()
            expect(output.properties.access_token).toBeDefined()
            expect(output.properties.refresh_token).toBeDefined()
            expect(output.properties.expires_in).toBeDefined()
        })
    })

    describe('jwt_refresh', () => {
        it('should be registered as a server function', () => {
            const fn = findFunction('jwt_refresh')
            expect(fn).toBeDefined()
            expect(fn?.transport).toBe('http')
        })

        it('should accept refresh_token as input', () => {
            const fn = findFunction('jwt_refresh')
            expect(fn?.hasInput).toBe(true)

            const schemas = (mizanSchema as any).components?.schemas
            const input = schemas?.jwtRefreshInput

            expect(input).toBeDefined()
            expect(input.properties.refresh_token).toBeDefined()
        })

        it('should return token pair with expected fields', () => {
            const schemas = (mizanSchema as any).components?.schemas
            const output = schemas?.jwtRefreshOutput

            expect(output).toBeDefined()
            expect(output.properties.access_token).toBeDefined()
            expect(output.properties.refresh_token).toBeDefined()
            expect(output.properties.expires_in).toBeDefined()
        })
    })
})
