import { logger } from "../logger/index.mjs";
import { formatPaginatedResponse, formatResponse } from "../utils/responseData.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";
import { hasPermission } from "../utils/permissions.mjs";
import { countUsers, createUser as createUser$1, deleteUser as deleteUser$1, findUsers, getUserByEmail as getUserByEmail$1, getUserById as getUserById$1, updateUserById } from "../services/user.service.mjs";
import { mapUserToAPI, mapUsersToAPI } from "../utils/mapper/user.mjs";
import { sendEmail } from "../services/email.service.mjs";
import { getUserFiltersAndPagination } from "../utils/filtersAndPagination/getUserFiltersAndPagination.mjs";
import { t } from "express-intlayer";

//#region src/controllers/user.controller.ts
/**
* Creates a new user.
*/
const createUser = async (req, res, _next) => {
	const user = req.body;
	if (!user) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	try {
		const newUser = await createUser$1(user);
		await sendEmail({
			type: "welcome",
			to: newUser.email,
			username: newUser.name,
			loginLink: `${process.env.CLIENT_URL}/auth/login`
		});
		const formattedUser = mapUserToAPI(newUser);
		const responseData = formatResponse({
			message: t({
				en: "User created",
				fr: "Utilisateur créé",
				es: "Usuario creado"
			}),
			description: t({
				en: "User created successfully",
				fr: "Utilisateur créé avec succès",
				es: "Usuario creado con éxito"
			}),
			data: formattedUser
		});
		res.json(responseData);
		return;
	} catch (error) {
		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) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	const { filters, sortOptions, pageSize, skip, page, getNumberOfPages } = getUserFiltersAndPagination(req, res);
	try {
		const users = await findUsers(filters, skip, pageSize, sortOptions);
		if (!hasPermission(roles, "user:read")({
			...res.locals,
			targetUsers: users
		})) {
			ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const totalItems = await countUsers(filters);
		const responseData = formatPaginatedResponse({
			data: mapUsersToAPI(users),
			page,
			pageSize,
			totalPages: getNumberOfPages(totalItems),
			totalItems
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const getUserById = async (req, res, _next) => {
	const { userId } = req.params;
	try {
		const user = await getUserById$1(userId);
		if (!user) {
			ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
			return;
		}
		const responseData = formatResponse({ data: mapUserToAPI(user) });
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const getUserByEmail = async (req, res, _next) => {
	const { email } = req.params;
	const { roles } = res.locals;
	try {
		const user = await getUserByEmail$1(email);
		if (!user) {
			ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
			return;
		}
		if (!hasPermission(roles, "user:read")({
			...res.locals,
			targetUsers: [user]
		})) {
			ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const responseData = formatResponse({ data: mapUserToAPI(user) });
		res.json(responseData);
	} catch (error) {
		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) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	if (typeof userData !== "object") {
		ErrorHandler.handleGenericErrorResponse(res, "USER_DATA_NOT_FOUND");
		return;
	}
	if (!userData.id) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_INVALID_FIELDS");
		return;
	}
	const userDB = await getUserById$1(userData.id);
	if (!userDB) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
		return;
	}
	if (!hasPermission(roles, "user:write")({
		...res.locals,
		targetUsers: [userDB]
	})) {
		ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
		return;
	}
	try {
		const updatedUser = await updateUserById(userDB.id, userData);
		logger.info(`User updated: Name: ${updatedUser.name}, id: ${String(updatedUser.id)}`);
		const formattedUser = mapUserToAPI(updatedUser);
		const responseData = formatResponse({
			message: t({
				en: "User updated",
				fr: "Utilisateur mis à jour",
				es: "Usuario actualizado"
			}),
			description: 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) {
		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 getUserById$1(userId);
		if (!user) {
			ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		if (!hasPermission(roles, "user:admin")({
			...res.locals,
			targetUsers: [user]
		})) {
			ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		await deleteUser$1(userId);
		const formattedUser = mapUserToAPI(user);
		const responseData = formatResponse({
			message: t({
				en: "User deleted",
				fr: "Utilisateur supprimé",
				es: "Usuario eliminado"
			}),
			description: t({
				en: "User deleted successfully",
				fr: "Utilisateur supprimé avec succès",
				es: "Usuario eliminado con éxito"
			}),
			data: formattedUser
		});
		res.json(responseData);
	} catch (error) {
		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 getUserById$1(userId);
	if (!user) {
		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
export { createUser, deleteUser, getUserByEmail, getUserById, getUsers, sendVerificationUpdate, updateUser, verifyEmailStatusSSE };
//# sourceMappingURL=user.controller.mjs.map