import { OIDCProvider } from '../src/provider';
import type { OIDCProviderConfig } from '../src/types';

// 模拟存储适配器
const mockStorage = {
    async set(key: string, value: any, ttl?: number): Promise<void> {
        console.log(`存储: ${key}`);
    },
    async get(key: string): Promise<any> {
        return null;
    },
    async delete(key: string): Promise<void> {
        console.log(`删除: ${key}`);
    }
};

// 基础配置
const baseConfig: Omit<OIDCProviderConfig, 'signingKey' | 'signingAlgorithm'> = {
    issuer: 'https://auth.example.com',
    storage: mockStorage,
    findUser: async (userId: string) => ({
        sub: userId,
        username: 'testuser',
        email: 'test@example.com'
    }),
    findClient: async (clientId: string) => ({
        client_id: clientId,
        client_type: 'public' as const,
        redirect_uris: ['http://localhost:3000/callback'],
        grant_types: ['authorization_code'],
        response_types: ['code'],
        scopes: ['openid', 'profile'],
        created_at: new Date(),
        updated_at: new Date()
    }),
    authConfig: {
        passwordValidator: async (username: string, password: string) => {
            return username === 'test' && password === 'password' ? 'user123' : null;
        }
    }
};

async function testAutoKeyGeneration() {
    console.log('=== 测试自动生成密钥对功能 ===\n');

    // 测试1: RS256算法自动生成RSA密钥对
    console.log('1. 测试RS256算法自动生成RSA密钥对:');
    try {
        const providerRS256 = new OIDCProvider({
            ...baseConfig,
            signingAlgorithm: 'RS256'
            // 注意：没有提供signingKey
        });

        const jwks = await providerRS256.getJWKS();
        console.log('✅ 成功生成RS256密钥对');
        console.log('JWKS keys count:', jwks.keys.length);
        console.log('First key algorithm:', jwks.keys[0]?.alg);
        console.log('');
    } catch (error) {
        console.error('❌ RS256测试失败:', error);
    }

    // 测试2: ES256算法自动生成ECDSA密钥对
    console.log('2. 测试ES256算法自动生成ECDSA密钥对:');
    try {
        const providerES256 = new OIDCProvider({
            ...baseConfig,
            signingAlgorithm: 'ES256'
            // 注意：没有提供signingKey
        });

        const jwks = await providerES256.getJWKS();
        console.log('✅ 成功生成ES256密钥对');
        console.log('JWKS keys count:', jwks.keys.length);
        console.log('First key algorithm:', jwks.keys[0]?.alg);
        console.log('');
    } catch (error) {
        console.error('❌ ES256测试失败:', error);
    }

    // 测试3: HS256算法没有signingKey应该失败
    console.log('3. 测试HS256算法没有signingKey应该失败:');
    try {
        const providerHS256 = new OIDCProvider({
            ...baseConfig,
            signingAlgorithm: 'HS256'
            // 注意：没有提供signingKey，应该失败
        });

        // 调用getJWKS触发验证
        await providerHS256.getJWKS();
        console.error('❌ HS256测试失败：应该抛出错误但没有');
    } catch (error) {
        console.log('✅ HS256测试成功：正确抛出错误');
        console.log('错误信息:', (error as Error).message);
        console.log('');
    }

    // 测试4: HS256算法提供signingKey应该成功
    console.log('4. 测试HS256算法提供signingKey应该成功:');
    try {
        const providerHS256 = new OIDCProvider({
            ...baseConfig,
            signingKey: 'my-secret-key-at-least-32-characters-long',
            signingAlgorithm: 'HS256'
        });

        const jwks = await providerHS256.getJWKS();
        console.log('✅ HS256测试成功');
        console.log('JWKS keys count:', jwks.keys.length, '(HS256不公开密钥)');
        console.log('');
    } catch (error) {
        console.error('❌ HS256测试失败:', error);
    }

    console.log('=== 测试完成 ===');
}

// 运行测试
testAutoKeyGeneration().catch(console.error); 