const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
const require_logger_index = require('../../logger/index.cjs');
const require_services_organization_service = require('../../services/organization.service.cjs');
const require_services_project_service = require('../../services/project.service.cjs');
const require_utils_permissions = require('../permissions.cjs');
const require_services_user_service = require('../../services/user.service.cjs');
const require_utils_mapper_user = require('../mapper/user.cjs');
const require_services_email_service = require('../../services/email.service.cjs');
const require_utils_mapper_organization = require('../mapper/organization.cjs');
const require_utils_mapper_project = require('../mapper/project.cjs');
const require_controllers_user_controller = require('../../controllers/user.controller.cjs');
const require_utils_mapper_session = require('../mapper/session.cjs');
let better_auth = require("better-auth");
better_auth = require_rolldown_runtime.__toESM(better_auth);
let better_auth_adapters_mongodb = require("better-auth/adapters/mongodb");
better_auth_adapters_mongodb = require_rolldown_runtime.__toESM(better_auth_adapters_mongodb);
let better_auth_api = require("better-auth/api");
better_auth_api = require_rolldown_runtime.__toESM(better_auth_api);
let better_auth_plugins = require("better-auth/plugins");
better_auth_plugins = require_rolldown_runtime.__toESM(better_auth_plugins);

//#region src/utils/auth/getAuth.ts
const formatSession = (session) => {
	const roles = require_utils_permissions.getSessionRoles(session);
	let permissions = require_utils_permissions.computeEffectivePermission(roles);
	if (session.permissions) permissions = require_utils_permissions.intersectPermissions(permissions, session.permissions);
	return {
		session: session.session,
		user: session.user,
		organization: session.organization,
		project: session.project,
		authType: "session",
		permissions,
		roles
	};
};
const getAuth = (dbClient) => {
	if (!dbClient) throw new Error("MongoDB connection not established");
	return (0, better_auth.betterAuth)({
		appName: "Intlayer",
		database: (0, better_auth_adapters_mongodb.mongodbAdapter)(dbClient.db()),
		user: { modelName: "users" },
		databaseHooks: { user: { create: { after: async (user) => {
			if (!user?.emailVerified) return;
			await require_services_email_service.sendEmail({
				type: "welcome",
				to: user.email,
				username: user.name ?? user.email.split("@")[0],
				loginLink: `${process.env.CLIENT_URL}/auth/login`,
				locale: user.lang
			});
			require_logger_index.logger.info("Welcome e‑mail delivered", { email: user.email });
		} } } },
		hooks: { after: (0, better_auth_api.createAuthMiddleware)(async (ctx) => {
			const { path, context } = ctx;
			const newUser = context.newSession?.user;
			const existingUser = context.session?.user;
			const user = newUser ?? existingUser;
			if (!user) return;
			if (["/verify-email"].includes(path)) {
				require_controllers_user_controller.sendVerificationUpdate(user);
				require_logger_index.logger.info("SSE verification update sent", {
					email: user.email,
					userId: user.id
				});
				await require_services_email_service.sendEmail({
					type: "welcome",
					to: user.email,
					username: user.name ?? user.email.split("@")[0],
					loginLink: `${process.env.CLIENT_URL}/auth/login`,
					locale: user.lang
				});
				require_logger_index.logger.info("Welcome e‑mail delivered", { email: user.email });
			}
		}) },
		advanced: {
			cookiePrefix: "intlayer",
			cookies: { session_token: {} }
		},
		secret: process.env.AUTH_SECRET,
		session: {
			modelName: "sessions",
			id: "id",
			additionalFields: {
				activeOrganizationId: {
					type: "string",
					nullable: true,
					input: false
				},
				activeProjectId: {
					type: "string",
					nullable: true,
					input: false
				}
			}
		},
		plugins: [(0, better_auth_plugins.customSession)(async ({ session }) => {
			const typedSession = session;
			let userAPI = null;
			let organizationAPI = null;
			let projectAPI = null;
			if (typedSession.userId) {
				const userData = await require_services_user_service.getUserById(typedSession.userId);
				if (userData) userAPI = require_utils_mapper_user.mapUserToAPI(userData);
			}
			if (typedSession.activeOrganizationId) {
				const orgData = await require_services_organization_service.getOrganizationById(typedSession.activeOrganizationId);
				if (orgData) organizationAPI = require_utils_mapper_organization.mapOrganizationToAPI(orgData);
			}
			if (typedSession.activeProjectId) {
				const projectData = await require_services_project_service.getProjectById(typedSession.activeProjectId);
				if (projectData) projectAPI = require_utils_mapper_project.mapProjectToAPI(projectData);
			}
			return require_utils_mapper_session.mapSessionToAPI(formatSession({
				session: typedSession,
				user: userAPI,
				organization: organizationAPI ?? null,
				project: projectAPI ?? null,
				authType: "session"
			}));
		})],
		emailAndPassword: {
			enabled: true,
			disableSignUp: false,
			requireEmailVerification: true,
			minPasswordLength: 8,
			maxPasswordLength: 128,
			autoSignIn: true,
			sendResetPassword: async ({ user, url }) => {
				require_logger_index.logger.info("sending reset password email", { email: user.email });
				await require_services_email_service.sendEmail({
					type: "resetPassword",
					to: user.email,
					username: user.name ?? user.email.split("@")[0],
					resetLink: url
				});
			},
			resetPasswordTokenExpiresIn: 3600
		},
		accountLinking: {
			enabled: true,
			trustedProviders: ["google", "github"]
		},
		emailVerification: {
			autoSignInAfterVerification: true,
			sendOnSignIn: true,
			sendVerificationEmail: async ({ user, url }) => {
				require_logger_index.logger.info("sending verification email", { email: user.email });
				await require_services_email_service.sendEmail({
					type: "validate",
					to: user.email,
					username: user.name ?? user.email.split("@")[0],
					validationLink: url
				});
			}
		},
		crossSubDomainCookies: {
			enabled: true,
			additionalCookies: ["session_token"],
			domain: process.env.CLIENT_URL
		},
		cookiePrefix: "intlayer",
		cookies: { session_token: {
			name: "session_token",
			attributes: {
				httpOnly: true,
				secure: true
			}
		} },
		trustedOrigins: [process.env.CLIENT_URL],
		socialProviders: {
			google: {
				clientId: process.env.GOOGLE_CLIENT_ID,
				clientSecret: process.env.GOOGLE_CLIENT_SECRET
			},
			github: {
				clientId: process.env.GITHUB_CLIENT_ID,
				clientSecret: process.env.GITHUB_CLIENT_SECRET
			}
		},
		logger: { log: (level, message, ...args) => require_logger_index.logger[level](message, ...args) }
	});
};

//#endregion
exports.formatSession = formatSession;
exports.getAuth = getAuth;
//# sourceMappingURL=getAuth.cjs.map