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 "fastify-intlayer";

//#region src/controllers/projectAccessKey.controller.ts
/**
* Adds a new access key to a project.
*/
const addNewAccessKey = async (request, reply) => {
	const { user, project, roles, permissions } = request.locals || {};
	const { grants, name, expiresAt } = request.body;
	if (!project) return ErrorHandler.handleGenericErrorResponse(reply, "PROJECT_NOT_DEFINED");
	if (!user) return ErrorHandler.handleGenericErrorResponse(reply, "USER_NOT_DEFINED");
	if (!hasPermission(roles || [], "project:write")({
		...request.locals,
		targetProjectIds: [project.id]
	})) return ErrorHandler.handleGenericErrorResponse(reply, "PERMISSION_DENIED");
	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
		});
		sendEmail({
			type: "oAuthTokenCreated",
			to: user.email,
			username: user.name,
			applicationName: newAccessKey.name ?? newAccessKey.clientId,
			scopes: newAccessKey.grants,
			tokenDetailsUrl: `${process.env.APP_URL}/oauth2/token`,
			securityLogUrl: `${process.env.APP_URL}/security-log`,
			supportUrl: `${process.env.APP_URL}/support`
		});
		return reply.send(responseData);
	} catch (error) {
		return ErrorHandler.handleAppErrorResponse(reply, error);
	}
};
/**
* Deletes an access key from a project.
*/
const deleteAccessKey = async (request, reply) => {
	const { user, project, roles } = request.locals || {};
	const { clientId } = request.body;
	if (!project) return ErrorHandler.handleGenericErrorResponse(reply, "PROJECT_NOT_DEFINED");
	if (!user) return ErrorHandler.handleGenericErrorResponse(reply, "USER_NOT_DEFINED");
	if (!clientId) return ErrorHandler.handleGenericErrorResponse(reply, "CLIENT_ID_NOT_FOUND");
	if (!hasPermission(roles || [], "project:write")({
		...request.locals,
		targetProjectIds: [project.id]
	})) return ErrorHandler.handleGenericErrorResponse(reply, "PERMISSION_DENIED");
	try {
		if (!await deleteAccessKey$1(clientId, project, user.id)) return ErrorHandler.handleGenericErrorResponse(reply, "ACCESS_KEY_NOT_FOUND", { clientId });
		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
		});
		return reply.send(responseData);
	} catch (error) {
		return ErrorHandler.handleAppErrorResponse(reply, error);
	}
};
/**
* Refreshes an access key from a project.
*/
const refreshAccessKey = async (request, reply) => {
	const { user, project, roles } = request.locals || {};
	const { clientId } = request.body;
	if (!project) return ErrorHandler.handleGenericErrorResponse(reply, "PROJECT_NOT_DEFINED");
	if (!user) return ErrorHandler.handleGenericErrorResponse(reply, "USER_NOT_DEFINED");
	if (!clientId) return ErrorHandler.handleGenericErrorResponse(reply, "CLIENT_ID_NOT_FOUND");
	if (!hasPermission(roles || [], "project:write")({
		...request.locals,
		targetProjectIds: [project?.id]
	})) return ErrorHandler.handleGenericErrorResponse(reply, "PERMISSION_DENIED");
	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
		});
		return reply.send(responseData);
	} catch (error) {
		return ErrorHandler.handleAppErrorResponse(reply, error);
	}
};

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