import { isPostgresMode } from '../config/persistence.js';
import { getPrismaClient } from '../db/prisma.js';
import { env, createLogger } from '@4runr/shared';
const logger = createLogger('Gateway:Auth:APIKey');
const memoryApiKeys = new Map();
function initializeMemoryApiKeys() {
    const apiKeys = process.env['API_KEY'] || process.env['API_KEYS'];
    if (apiKeys) {
        const keys = apiKeys.split(',').map(k => k.trim()).filter(Boolean);
        keys.forEach((key, index) => {
            memoryApiKeys.set(key, {
                label: `Memory Key ${index + 1}`,
                revoked: false,
            });
        });
    }
    const singleKey = process.env['API_KEY'];
    if (singleKey && !apiKeys?.includes(',')) {
        memoryApiKeys.set(singleKey, {
            label: 'Default API Key',
            revoked: false,
        });
    }
}
initializeMemoryApiKeys();
async function validateApiKey(key) {
    if (isPostgresMode()) {
        try {
            const prisma = await getPrismaClient();
            const apiKey = await prisma.apiKey.findUnique({
                where: { key },
            });
            if (!apiKey) {
                return { valid: false, revoked: false };
            }
            return {
                valid: true,
                revoked: apiKey.revoked,
            };
        }
        catch (error) {
            logger.error('Error validating API key', { error: error instanceof Error ? error.message : String(error) });
            return { valid: false, revoked: false };
        }
    }
    else {
        const apiKey = memoryApiKeys.get(key);
        if (!apiKey) {
            return { valid: false, revoked: false };
        }
        return {
            valid: true,
            revoked: apiKey.revoked,
        };
    }
}
export async function requireApiKey(request, reply) {
    if (!env.AUTH_ENABLED) {
        return;
    }
    const url = request.url || '/';
    const path = url.split('?')[0] || '/';
    if (path === '/health' ||
        path === '/ready' ||
        path === '/liveness' ||
        path === '/startup' ||
        path === '/metrics' ||
        (path && path.startsWith('/debug/'))) {
        return;
    }
    const apiKey = request.headers['x-api-key'];
    if (!apiKey) {
        reply.status(401).send({
            error: 'Unauthorized',
            message: 'Missing x-api-key header',
        });
        return;
    }
    const validation = await validateApiKey(apiKey);
    if (!validation.valid) {
        reply.status(401).send({
            error: 'Unauthorized',
            message: 'Invalid API key',
        });
        return;
    }
    if (validation.revoked) {
        reply.status(403).send({
            error: 'Forbidden',
            message: 'API key has been revoked',
        });
        return;
    }
    request.apiKey = apiKey;
}
export async function optionalApiKey(request, reply) {
    const apiKey = request.headers['x-api-key'];
    if (apiKey) {
        const validation = await validateApiKey(apiKey);
        if (validation.valid && !validation.revoked) {
            request.apiKey = apiKey;
        }
    }
}
//# sourceMappingURL=authApiKey.js.map