import { respondWithMiddlewareFailure, } from './MiddlewareFailureResponder.js';
const createAuthFailureBody = (reason, message) => ({
    error: {
        code: reason,
        message,
    },
});
export const AuthMiddleware = Object.freeze({
    create(options = {}) {
        const headerName = (options.headerName ?? 'authorization').toLowerCase();
        const message = options.message ?? 'Unauthorized';
        return async (req, res, next) => {
            const header = req.getHeader(headerName);
            const value = Array.isArray(header) ? header[0] : header;
            if (typeof value !== 'string' || value.trim() === '') {
                await respondWithMiddlewareFailure(req, res, options.onUnauthorized, {
                    middleware: 'auth',
                    reason: 'missing_authorization_header',
                    statusCode: 401,
                    message,
                    body: createAuthFailureBody('missing_authorization_header', message),
                });
                return;
            }
            await next();
        };
    },
});
export default AuthMiddleware;
