import { logger } from "../logger/index.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";
import { formatSession } from "../utils/auth/getAuth.mjs";
import { authenticateOptions, getAuthModel } from "../utils/oAuth2.mjs";
import { getOAuth2AccessTokenContext, validateOAuth2AccessToken } from "../services/oAuth2.service.mjs";
import OAuth2Server, { Request, Response } from "oauth2-server";

//#region src/middlewares/oAuth2.middleware.ts
const oauth = new OAuth2Server({
	model: 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 Request(req);
		const oauthResponse = new Response(res);
		const formattedSession = formatSession(await getOAuth2AccessTokenContext(await validateOAuth2AccessToken((await req.oauth.authenticate(oauthRequest, oauthResponse, authenticateOptions)).accessToken)));
		res.locals.authType = "session";
		Object.entries(formattedSession).forEach(([key, value]) => {
			res.locals[key] = value;
		});
		logger.info("OAuth2 bearer token authenticated", formattedSession.user.email);
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
	next();
};

//#endregion
export { attachOAuthInstance, oAuth2Middleware };
//# sourceMappingURL=oAuth2.middleware.mjs.map