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');
const require_services_email_service = require('../services/email.service.cjs');
const require_utils_filtersAndPagination_getUserFiltersAndPagination = require('../utils/filtersAndPagination/getUserFiltersAndPagination.cjs');
let express_intlayer = require("express-intlayer");
express_intlayer = require_rolldown_runtime.__toESM(express_intlayer);

//#region src/controllers/user.controller.ts
/**
* Creates a new user.
*/
const createUser = async (req, res, _next) => {
	const user = req.body;
	if (!user) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	try {
		const newUser = await require_services_user_service.createUser(user);
		await require_services_email_service.sendEmail({
			type: "welcome",
			to: newUser.email,
			username: newUser.name,
			loginLink: `${process.env.CLIENT_URL}/auth/login`
		});
		const formattedUser = require_utils_mapper_user.mapUserToAPI(newUser);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "User created",
				fr: "Utilisateur créé",
				es: "Usuario creado"
			}),
			description: (0, express_intlayer.t)({
				en: "User created successfully",
				fr: "Utilisateur créé avec succès",
				es: "Usuario creado con éxito"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of users based on filters and pagination.
*/
const getUsers = async (req, res, _next) => {
	const { user, roles } = res.locals;
	if (!user) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	const { filters, sortOptions, pageSize, skip, page, getNumberOfPages } = require_utils_filtersAndPagination_getUserFiltersAndPagination.getUserFiltersAndPagination(req, res);
	try {
		const users = await require_services_user_service.findUsers(filters, skip, pageSize, sortOptions);
		if (!require_utils_permissions.hasPermission(roles, "user:read")({
			...res.locals,
			targetUsers: users
		})) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const totalItems = await require_services_user_service.countUsers(filters);
		const responseData = require_utils_responseData.formatPaginatedResponse({
			data: require_utils_mapper_user.mapUsersToAPI(users),
			page,
			pageSize,
			totalPages: getNumberOfPages(totalItems),
			totalItems
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const getUserById = async (req, res, _next) => {
	const { userId } = req.params;
	try {
		const user = await require_services_user_service.getUserById(userId);
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: require_utils_mapper_user.mapUserToAPI(user) });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const getUserByEmail = async (req, res, _next) => {
	const { email } = req.params;
	const { roles } = res.locals;
	try {
		const user = await require_services_user_service.getUserByEmail(email);
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
			return;
		}
		if (!require_utils_permissions.hasPermission(roles, "user:read")({
			...res.locals,
			targetUsers: [user]
		})) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: require_utils_mapper_user.mapUserToAPI(user) });
		res.json(responseData);
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Updates user information (phone number, date of birth).
*/
const updateUser = async (req, res, _next) => {
	const userData = req.body;
	const { user, roles } = res.locals;
	if (!user) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	if (typeof userData !== "object") {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_DATA_NOT_FOUND");
		return;
	}
	if (!userData.id) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_INVALID_FIELDS");
		return;
	}
	const userDB = await require_services_user_service.getUserById(userData.id);
	if (!userDB) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
		return;
	}
	if (!require_utils_permissions.hasPermission(roles, "user:write")({
		...res.locals,
		targetUsers: [userDB]
	})) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
		return;
	}
	try {
		const updatedUser = await require_services_user_service.updateUserById(userDB.id, userData);
		require_logger_index.logger.info(`User updated: Name: ${updatedUser.name}, id: ${String(updatedUser.id)}`);
		const formattedUser = require_utils_mapper_user.mapUserToAPI(updatedUser);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "User updated",
				fr: "Utilisateur mis à jour",
				es: "Usuario actualizado"
			}),
			description: (0, express_intlayer.t)({
				en: "User updated successfully",
				fr: "Utilisateur mis à jour avec succès",
				es: "Usuario actualizado con éxito"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Deletes a user based on the provided ID.
*/
const deleteUser = async (req, res, _next) => {
	const { userId } = req.params;
	const { roles } = res.locals;
	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:admin")({
			...res.locals,
			targetUsers: [user]
		})) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		await require_services_user_service.deleteUser(userId);
		const formattedUser = require_utils_mapper_user.mapUserToAPI(user);
		const responseData = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "User deleted",
				fr: "Utilisateur supprimé",
				es: "Usuario eliminado"
			}),
			description: (0, express_intlayer.t)({
				en: "User deleted successfully",
				fr: "Utilisateur supprimé avec succès",
				es: "Usuario eliminado con éxito"
			}),
			data: formattedUser
		});
		res.json(responseData);
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
let clients = [];
const sendVerificationUpdate = (user) => {
	const filteredClients = clients.filter((client) => String(client.userId) === String(user.id));
	for (const client of filteredClients) if (user.emailVerified) client.res.write(`data: ${JSON.stringify({
		userId: user.id,
		status: "verified"
	})}\n\n`);
};
/**
* SSE to check the email verification status
*/
const verifyEmailStatusSSE = async (req, res) => {
	res.setHeader("Content-Type", "text/event-stream;charset=utf-8");
	res.setHeader("Cache-Control", "no-cache, no-transform");
	res.setHeader("Connection", "keep-alive");
	res.setHeader("X-Accel-Buffering", "no");
	res.write(":\n\n");
	res.flushHeaders();
	const { userId } = req.params;
	const clientId = Date.now();
	const user = await require_services_user_service.getUserById(userId);
	if (!user) {
		require_logger_index.logger.error(`User not found - User ID: ${userId}`);
		res.write(`data: ${JSON.stringify({
			userId,
			status: "error"
		})}\n\n`);
		res.end();
		return;
	}
	const newClient = {
		id: clientId,
		userId,
		res
	};
	clients.push(newClient);
	sendVerificationUpdate(user);
	req.on("close", () => {
		clients = clients.filter((client) => client.id !== clientId);
	});
};

//#endregion
exports.createUser = createUser;
exports.deleteUser = deleteUser;
exports.getUserByEmail = getUserByEmail;
exports.getUserById = getUserById;
exports.getUsers = getUsers;
exports.sendVerificationUpdate = sendVerificationUpdate;
exports.updateUser = updateUser;
exports.verifyEmailStatusSSE = verifyEmailStatusSSE;
//# sourceMappingURL=user.controller.cjs.map