import { getCredentialsStore } from '../ai-providers/redis-credentials-store.js';
import { requireAuth } from '../middleware/auth.js';
import { readRateLimit, writeRateLimit } from '../middleware/rateLimit.js';
import { isRedisAvailable } from '../db/redis.js';
let credentialsStore = null;
function getStore() {
    if (!credentialsStore) {
        credentialsStore = getCredentialsStore();
    }
    return credentialsStore;
}
export async function aiProviderRoutes(fastify) {
    fastify.post('/api/ai-providers/credentials', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const redisOk = await isRedisAvailable();
            if (!redisOk) {
                return reply.status(503).send({
                    error: 'Redis not available',
                    message: 'Credential storage requires Redis. Please configure REDIS_URL or start Redis.',
                });
            }
            const { provider, apiKey } = (request.body || {});
            if (!provider || !apiKey) {
                return reply.status(400).send({
                    error: 'Missing required fields',
                    required: ['provider', 'apiKey'],
                });
            }
            await getStore().setCredential(provider, apiKey);
            console.log(`[AIProviders] Credential stored in Redis: ${provider}`);
            return reply.status(201).send({
                success: true,
                message: 'Credential stored successfully (encrypted in Redis)',
                provider,
                persistent: true,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[AIProviders] Error storing credential:', msg);
            return reply.status(500).send({
                error: 'Failed to store credential',
                details: msg,
            });
        }
    });
    fastify.post('/api/ai-providers/test', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const redisOk = await isRedisAvailable();
            if (!redisOk) {
                return reply.status(503).send({
                    success: false,
                    error: 'Redis not available',
                    message: 'Credential storage requires Redis',
                });
            }
            const { provider } = (request.body || {});
            if (!provider) {
                return reply.status(400).send({
                    success: false,
                    error: 'Missing provider',
                    message: 'Request body must include provider',
                });
            }
            const hasCredential = await getStore().hasCredential(provider);
            if (!hasCredential) {
                return reply.status(400).send({
                    success: false,
                    error: 'Provider not configured',
                    message: `No API key found for ${provider} in Redis`,
                });
            }
            return reply.status(200).send({
                success: true,
                provider,
                message: 'Connection test successful (key found in Redis)',
                configured: true,
                persistent: true,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[AIProviders] Error testing provider:', msg);
            return reply.status(500).send({
                error: 'Failed to test provider',
                details: msg,
            });
        }
    });
    fastify.get('/api/ai-providers', {
        preHandler: [requireAuth, readRateLimit],
    }, async (_request, reply) => {
        try {
            const redisOk = await isRedisAvailable();
            if (!redisOk) {
                return reply.status(200).send({
                    success: true,
                    providers: [],
                    total: 0,
                    storage: 'Redis (unavailable)',
                });
            }
            const providerList = await getStore().listProviders();
            const configuredProviders = providerList.map((provider) => ({
                provider,
                configured: true,
                models: getModelsForProvider(provider),
                persistent: true,
            }));
            return reply.status(200).send({
                success: true,
                providers: configuredProviders,
                total: configuredProviders.length,
                storage: 'Redis (encrypted)',
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[AIProviders] Error listing providers:', msg);
            return reply.status(500).send({
                error: 'Failed to list providers',
                details: msg,
            });
        }
    });
    fastify.delete('/api/ai-providers/credentials/:provider', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const redisOk = await isRedisAvailable();
            if (!redisOk) {
                return reply.status(503).send({
                    error: 'Redis not available',
                    message: 'Credential storage requires Redis',
                });
            }
            const { provider } = request.params;
            const hasCredential = await getStore().hasCredential(provider);
            if (!hasCredential) {
                return reply.status(404).send({
                    error: 'Provider not found in Redis',
                    provider,
                });
            }
            await getStore().deleteCredential(provider);
            console.log(`[AIProviders] Credential removed from Redis: ${provider}`);
            return reply.status(200).send({
                success: true,
                message: 'Credential removed from Redis successfully',
                provider,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[AIProviders] Error removing credential:', msg);
            return reply.status(500).send({
                error: 'Failed to remove credential',
                details: msg,
            });
        }
    });
}
function getModelsForProvider(provider) {
    const modelMap = {
        openai: ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo'],
        anthropic: ['claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307'],
        google: ['gemini-pro', 'gemini-pro-vision'],
    };
    return modelMap[provider] || [];
}
//# sourceMappingURL=ai-providers-simple.js.map