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 (request, _reply) => {
	request.oauth = oauth;
};
const oAuth2Middleware = async (request, reply) => {
	if (!request.locals) request.locals = {};
	if (typeof request.locals?.authType !== "undefined") return;
	try {
		if (!Boolean(request.headers.authorization)) return;
		const oauthRequest = new Request({
			headers: request.headers,
			method: request.method,
			query: request.query,
			body: request.body
		});
		const oauthResponse = new Response(reply.raw);
		const formattedSession = formatSession(await getOAuth2AccessTokenContext(await validateOAuth2AccessToken((await request.oauth.authenticate(oauthRequest, oauthResponse, authenticateOptions)).accessToken)));
		const locals = request.locals;
		if (locals) {
			locals.authType = "session";
			for (const [key, value] of Object.entries(formattedSession)) locals[key] = value;
		}
		logger.info("OAuth2 bearer token authenticated", formattedSession.user.email);
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(reply, error);
		return;
	}
};

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