import { env } from '@4runr/shared';
import { requireApiKey } from './authApiKey.js';
import { requireJwt } from './authJwt.js';
export async function requireAuth(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/')) ||
        (path && path.startsWith('/devkit/'))) {
        return;
    }
    const authMode = env.AUTH_MODE;
    if (authMode === 'api_key') {
        await requireApiKey(request, reply);
        return;
    }
    if (authMode === 'jwt') {
        await requireJwt(request, reply);
        return;
    }
    if (authMode === 'mixed') {
        const hasApiKey = !!request.headers['x-api-key'];
        const hasBearer = !!request.headers.authorization?.startsWith('Bearer ');
        if (hasApiKey) {
            await requireApiKey(request, reply);
            return;
        }
        if (hasBearer) {
            await requireJwt(request, reply);
            return;
        }
        reply.status(401).send({
            error: 'unauthorized',
            reason: 'invalid_or_missing_credentials',
            message: 'Authentication required. Provide either x-api-key header or Authorization: Bearer <token>',
        });
        return;
    }
    await requireApiKey(request, reply);
}
export function getAuthIdentity(request) {
    const apiKey = request.apiKey;
    if (apiKey) {
        return `apikey:${apiKey.substring(0, 8)}...`;
    }
    const auth = request.auth || request.user;
    if (auth) {
        return auth.sub || auth.tenantId || 'jwt:unknown';
    }
    return undefined;
}
export function isAuthenticated(request) {
    return !!(request.apiKey ||
        request.auth ||
        request.user);
}
//# sourceMappingURL=auth.js.map