const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_logger_index = require('../logger/index.cjs');
const require_utils_errors_ErrorHandler = require('../utils/errors/ErrorHandler.cjs');
const require_utils_auth_getAuth = require('../utils/auth/getAuth.cjs');
const require_utils_oAuth2 = require('../utils/oAuth2.cjs');
const require_services_oAuth2_service = require('../services/oAuth2.service.cjs');
let oauth2_server = require("oauth2-server");
oauth2_server = require_rolldown_runtime.__toESM(oauth2_server);

//#region src/middlewares/oAuth2.middleware.ts
const oauth = new oauth2_server.default({
	model: require_utils_oAuth2.getAuthModel(),
	accessTokenLifetime: 3600,
	allowBearerTokensInQueryString: true
});
const attachOAuthInstance = async (req, _res, next) => {
	req.oauth = oauth;
	next();
};
const oAuth2Middleware = async (req, res, next) => {
	if (typeof res.locals.authType !== "undefined") return next();
	try {
		if (!Boolean(req.headers.authorization)) return next();
		const oauthRequest = new oauth2_server.Request(req);
		const oauthResponse = new oauth2_server.Response(res);
		const formattedSession = require_utils_auth_getAuth.formatSession(await require_services_oAuth2_service.getOAuth2AccessTokenContext(await require_services_oAuth2_service.validateOAuth2AccessToken((await req.oauth.authenticate(oauthRequest, oauthResponse, require_utils_oAuth2.authenticateOptions)).accessToken)));
		res.locals.authType = "session";
		Object.entries(formattedSession).forEach(([key, value]) => {
			res.locals[key] = value;
		});
		require_logger_index.logger.info("OAuth2 bearer token authenticated", formattedSession.user.email);
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
	next();
};

//#endregion
exports.attachOAuthInstance = attachOAuthInstance;
exports.oAuth2Middleware = oAuth2Middleware;
//# sourceMappingURL=oAuth2.middleware.cjs.map