import { formatResponse } from "../utils/responseData.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";
import { hasPermission, intersectPermissions } from "../utils/permissions.mjs";
import { sendEmail } from "../services/email.service.mjs";
import { addNewAccessKey as addNewAccessKey$1, deleteAccessKey as deleteAccessKey$1, refreshAccessKey as refreshAccessKey$1 } from "../services/projectAccessKey.service.mjs";
import { t } from "express-intlayer";

//#region src/controllers/projectAccessKey.controller.ts
/**
* Adds a new access key to a project.
*/
const addNewAccessKey = async (req, res, _next) => {
	const { user, project, roles, permissions } = res.locals;
	const { grants, name, expiresAt } = req.body;
	if (!project) {
		ErrorHandler.handleGenericErrorResponse(res, "PROJECT_NOT_DEFINED");
		return;
	}
	if (!user) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	if (!hasPermission(roles, "project:write")({
		...res.locals,
		targetProjectIds: [project.id]
	})) {
		ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
		return;
	}
	const filteredPermisions = intersectPermissions(permissions, grants);
	try {
		const newAccessKey = await addNewAccessKey$1({
			name,
			expiresAt,
			grants: filteredPermisions
		}, project.id, user);
		const responseData = formatResponse({
			message: t({
				en: "Access key created successfully",
				es: "Clave de acceso creada con éxito",
				fr: "Clé d'accès créée avec succès"
			}),
			description: t({
				en: "The access key has been created successfully",
				es: "La clave de acceso ha sido creada con éxito",
				fr: "La clé d'accès a été créée avec succès"
			}),
			data: newAccessKey
		});
		res.json(responseData);
		sendEmail({
			type: "oAuthTokenCreated",
			to: user.email,
			username: user.name,
			applicationName: newAccessKey.name ?? newAccessKey.clientId,
			scopes: newAccessKey.grants,
			tokenDetailsUrl: `${process.env.CLIENT_URL}/oauth2/token`,
			securityLogUrl: `${process.env.CLIENT_URL}/security-log`,
			supportUrl: `${process.env.CLIENT_URL}/support`
		});
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Deletes an access key from a project.
*/
const deleteAccessKey = async (req, res, _next) => {
	const { user, project, roles } = res.locals;
	const { clientId } = req.body;
	if (!project) {
		ErrorHandler.handleGenericErrorResponse(res, "PROJECT_NOT_DEFINED");
		return;
	}
	if (!user) {
		ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	if (!clientId) {
		ErrorHandler.handleGenericErrorResponse(res, "CLIENT_ID_NOT_FOUND");
		return;
	}
	if (!hasPermission(roles, "project:write")({
		...res.locals,
		targetProjectIds: [project.id]
	})) {
		ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
		return;
	}
	try {
		if (!await deleteAccessKey$1(clientId, project, user.id)) {
			ErrorHandler.handleGenericErrorResponse(res, "ACCESS_KEY_NOT_FOUND", { clientId });
			return;
		}
		const responseData = formatResponse({
			message: t({
				en: "Access key deleted successfully",
				es: "Clave de acceso eliminada con éxito",
				fr: "Clé d'accès supprimée avec succès"
			}),
			description: t({
				en: "The access key has been deleted successfully",
				es: "La clave de acceso ha sido eliminada con éxito",
				fr: "La clé d'accès a été supprimée avec succès"
			}),
			data: null
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Refreshes an access key from a project.
*/
const refreshAccessKey = async (req, res, _next) => {
	const { user, project, roles } = res.locals;
	const { clientId } = req.body;
	if (!project) ErrorHandler.handleGenericErrorResponse(res, "PROJECT_NOT_DEFINED");
	if (!user) ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
	if (!clientId) ErrorHandler.handleGenericErrorResponse(res, "CLIENT_ID_NOT_FOUND");
	if (!hasPermission(roles, "project:write")({
		...res.locals,
		targetProjectIds: [project?.id]
	})) {
		ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
		return;
	}
	try {
		const newAccessKey = await refreshAccessKey$1(clientId, project?.id, user?.id);
		const responseData = formatResponse({
			message: t({
				en: "Access key refreshed successfully",
				es: "Clave de acceso actualizada con éxito",
				fr: "Clé d'accès actualisée avec succès"
			}),
			description: t({
				en: "The access key has been refreshed successfully",
				es: "La clave de acceso ha sido actualizada con éxito",
				fr: "La clé d'accès a été actualisée avec succès"
			}),
			data: newAccessKey
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};

//#endregion
export { addNewAccessKey, deleteAccessKey, refreshAccessKey };
//# sourceMappingURL=projectAccessKey.controller.mjs.map