const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_logger_index = require('../logger/index.cjs');
const require_utils_responseData = require('../utils/responseData.cjs');
const require_utils_errors_ErrorHandler = require('../utils/errors/ErrorHandler.cjs');
const require_utils_permissions = require('../utils/permissions.cjs');
const require_services_user_service = require('../services/user.service.cjs');
const require_utils_mapper_user = require('../utils/mapper/user.cjs');
let express_intlayer = require("express-intlayer");

//#region src/controllers/newsletter.controller.ts
/**
* Subscribes a user to the newsletter.
* If the user doesn't exist, creates a new user.
* If the user exists, updates their newsletter subscription to true.
*/
const subscribeToNewsletter = async (req, res, _next) => {
	const { roles } = res.locals;
	const { email, emailList } = req.body;
	if (!email) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_DATA_NOT_FOUND");
		return;
	}
	const emailLists = Array.isArray(emailList) ? emailList : [emailList];
	const emailsListObject = Object.fromEntries(emailLists.map((list) => [list, true]));
	try {
		let user = await require_services_user_service.getUserByEmail(email);
		if (!user) {
			user = await require_services_user_service.createUser({
				email,
				emailsList: emailsListObject
			});
			require_logger_index.logger.info(`New user created and subscribed to newsletter: ${email}`);
		} else {
			if (!require_utils_permissions.hasPermission(roles, "user:write")({
				...res.locals,
				targetUsers: [user]
			})) {
				require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
				return;
			}
			user = await require_services_user_service.updateUserById(user.id, { emailsList: {
				...user.emailsList,
				...emailsListObject
			} });
			require_logger_index.logger.info(`User subscribed to newsletter: ${email}`);
		}
		const formattedUser = require_utils_mapper_user.mapUserToAPI(user);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "Successfully subscribed to newsletter",
				fr: "Abonnement à la newsletter réussi",
				es: "Suscripción al boletín exitosa"
			}),
			description: (0, express_intlayer.t)({
				en: "You have been successfully subscribed to our newsletter",
				fr: "Vous avez été abonné avec succès à notre newsletter",
				es: "Te has suscrito exitosamente a nuestro boletín"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Unsubscribes a user from the newsletter.
* Only works if the user exists.
*/
const unsubscribeFromNewsletter = async (req, res, _next) => {
	const { userId, emailList } = req.body;
	const { roles } = res.locals;
	if (!userId) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_DATA_NOT_FOUND");
		return;
	}
	try {
		const user = await require_services_user_service.getUserById(userId);
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		if (!require_utils_permissions.hasPermission(roles, "user:write")({
			...res.locals,
			targetUsers: [user]
		})) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const emailLists = Array.isArray(emailList) ? emailList : [emailList];
		const emailsListObject = Object.fromEntries(emailLists.map((list) => [list, false]));
		const updatedUser = await require_services_user_service.updateUserById(user.id, { emailsList: {
			...user.emailsList,
			...emailsListObject
		} });
		require_logger_index.logger.info(`User unsubscribed from newsletter: ${updatedUser.email}`);
		const formattedUser = require_utils_mapper_user.mapUserToAPI(updatedUser);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "Successfully unsubscribed from newsletter",
				fr: "Désabonnement de la newsletter réussi",
				es: "Cancelación de suscripción al boletín exitosa"
			}),
			description: (0, express_intlayer.t)({
				en: "You have been successfully unsubscribed from our newsletter",
				fr: "Vous avez été désabonné avec succès de notre newsletter",
				es: "Te has desuscrito exitosamente de nuestro boletín"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Gets the newsletter subscription status for a user.
*/
const getNewsletterStatus = async (_req, res, _next) => {
	const email = res.locals.user?.email;
	const { roles } = res.locals;
	if (!email) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_DATA_NOT_FOUND");
		return;
	}
	try {
		const user = await require_services_user_service.getUserByEmail(email);
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		if (!require_utils_permissions.hasPermission(roles, "user:read")({
			...res.locals,
			targetUsers: [user]
		})) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const formattedUser = require_utils_mapper_user.mapUserToAPI(user);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "Newsletter subscription status retrieved",
				fr: "Statut d'abonnement à la newsletter récupéré",
				es: "Estado de suscripción al boletín obtenido"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};

//#endregion
exports.getNewsletterStatus = getNewsletterStatus;
exports.subscribeToNewsletter = subscribeToNewsletter;
exports.unsubscribeFromNewsletter = unsubscribeFromNewsletter;
//# sourceMappingURL=newsletter.controller.cjs.map