function writeDisabledResponse(res) {
    res.status(401).json({
        error: 'Unauthorized',
        message: 'Programmatic API is disabled: ADMIN_API_KEY is not configured.',
        timestamp: new Date().toISOString()
    });
}
function writeUnauthorized(res) {
    res.status(401).json({
        error: 'Unauthorized',
        message: 'Programmatic routes require Authorization: Bearer <key> or X-API-Key.',
        timestamp: new Date().toISOString()
    });
}
function readBearerToken(req) {
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
        return null;
    }
    const token = authHeader.slice(7).trim();
    return token === '' ? null : token;
}
function readApiKeyHeader(req) {
    const apiKeyHeader = req.headers['x-api-key'];
    if (typeof apiKeyHeader !== 'string') {
        return null;
    }
    const value = apiKeyHeader.trim();
    return value === '' ? null : value;
}
export function createProgrammaticAuthMiddleware(config) {
    return (req, res, next) => {
        const expectedKey = config.expectedKey?.trim();
        if (!expectedKey) {
            writeDisabledResponse(res);
            return;
        }
        const bearerToken = readBearerToken(req);
        if (bearerToken === expectedKey) {
            next();
            return;
        }
        const apiKeyHeader = readApiKeyHeader(req);
        if (apiKeyHeader === expectedKey) {
            next();
            return;
        }
        writeUnauthorized(res);
    };
}
//# sourceMappingURL=programmatic-auth.middleware.js.map