import { HttpStatusCodes } from "../utils/httpStatusCodes.mjs";
import { formatPaginatedResponse, formatResponse } from "../utils/responseData.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";
import { t } from "express-intlayer";
import * as auditService from "@services/audit.service";

//#region src/controllers/audit.controller.ts
/**
* Creates a new audit in the database.
*/
const createAudit = async (req, res, _next) => {
	const auditData = req.body;
	const auditApiKey = req.headers["x-audit-api-key"];
	if (!process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "AUDIT_API_KEY_NOT_CONFIGURED", {
			en: "Audit API Key Not Configured",
			fr: "Clé API d'audit non configurée",
			es: "Clave API de auditoría no configurada"
		}, {
			en: "AUDIT_API_KEY environment variable is not set on the server",
			fr: "La variable d'environnement AUDIT_API_KEY n'est pas définie sur le serveur",
			es: "La variable de entorno AUDIT_API_KEY no está configurada en el servidor"
		}, void 0, HttpStatusCodes.INTERNAL_SERVER_ERROR_500);
		return;
	}
	if (auditApiKey !== process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "INVALID_AUDIT_API_KEY", {
			en: "Invalid Audit API Key",
			fr: "Clé API d'audit invalide",
			es: "Clave API de auditoría inválida"
		}, {
			en: "The provided audit API key is invalid",
			fr: "La clé API d'audit fournie est invalide",
			es: "La clave API de auditoría proporcionada es inválida"
		}, void 0, HttpStatusCodes.UNAUTHORIZED_401);
		return;
	}
	if (!auditData) {
		ErrorHandler.handleGenericErrorResponse(res, "INVALID_REQUEST_BODY");
		return;
	}
	try {
		const { user, project } = res.locals;
		const audit = {
			...auditData,
			userId: user?.id,
			projectId: project?.id
		};
		const newAudit = await auditService.createAudit(audit);
		const responseData = formatResponse({
			message: t({
				en: "Audit created successfully",
				fr: "Audit créé avec succès",
				es: "Auditoría creada con éxito"
			}),
			description: t({
				en: "Your audit has been saved successfully",
				fr: "Votre audit a été enregistré avec succès",
				es: "Su auditoría ha sido guardada con éxito"
			}),
			data: newAudit.toJSON()
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves audits for the current user or project.
*/
const getAudits = async (req, res, _next) => {
	const auditApiKey = req.headers["x-audit-api-key"];
	if (!process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "AUDIT_API_KEY_NOT_CONFIGURED", {
			en: "Audit API Key Not Configured",
			fr: "Clé API d'audit non configurée",
			es: "Clave API de auditoría no configurada"
		}, {
			en: "AUDIT_API_KEY environment variable is not set on the server",
			fr: "La variable d'environnement AUDIT_API_KEY n'est pas définie sur le serveur",
			es: "La variable de entorno AUDIT_API_KEY no está configurada en el servidor"
		}, void 0, HttpStatusCodes.INTERNAL_SERVER_ERROR_500);
		return;
	}
	if (auditApiKey !== process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "INVALID_AUDIT_API_KEY", {
			en: "Invalid Audit API Key",
			fr: "Clé API d'audit invalide",
			es: "Clave API de auditoría inválida"
		}, {
			en: "The provided audit API key is invalid",
			fr: "La clé API d'audit fournie est invalide",
			es: "La clave API de auditoría proporcionada es inválida"
		}, void 0, HttpStatusCodes.UNAUTHORIZED_401);
		return;
	}
	try {
		const { user, project } = res.locals;
		const page = Number(req.query.page) || 1;
		const pageSize = Number(req.query.pageSize) || 20;
		const skip = (page - 1) * pageSize;
		let audits;
		if (project) audits = await auditService.findAuditsByProjectId(project.id, pageSize, skip);
		else if (user) audits = await auditService.findAuditsByUserId(user.id, pageSize, skip);
		else audits = [];
		const totalItems = audits.length;
		const responseData = formatPaginatedResponse({
			data: audits.map((audit) => audit.toJSON()),
			page,
			pageSize,
			totalPages: Math.ceil(totalItems / pageSize),
			totalItems
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves an audit by its ID.
*/
const getAuditById = async (req, res, _next) => {
	const { auditId } = req.params;
	const auditApiKey = req.headers["x-audit-api-key"];
	if (!process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "AUDIT_API_KEY_NOT_CONFIGURED", {
			en: "Audit API Key Not Configured",
			fr: "Clé API d'audit non configurée",
			es: "Clave API de auditoría no configurada"
		}, {
			en: "AUDIT_API_KEY environment variable is not set on the server",
			fr: "La variable d'environnement AUDIT_API_KEY n'est pas définie sur le serveur",
			es: "La variable de entorno AUDIT_API_KEY no está configurada en el servidor"
		}, void 0, HttpStatusCodes.INTERNAL_SERVER_ERROR_500);
		return;
	}
	if (auditApiKey !== process.env.AUDIT_API_KEY) {
		ErrorHandler.handleCustomErrorResponse(res, "INVALID_AUDIT_API_KEY", {
			en: "Invalid Audit API Key",
			fr: "Clé API d'audit invalide",
			es: "Clave API de auditoría inválida"
		}, {
			en: "The provided audit API key is invalid",
			fr: "La clé API d'audit fournie est invalide",
			es: "La clave API de auditoría proporcionada es inválida"
		}, void 0, HttpStatusCodes.UNAUTHORIZED_401);
		return;
	}
	if (!auditId) {
		ErrorHandler.handleGenericErrorResponse(res, "INVALID_REQUEST_BODY");
		return;
	}
	try {
		const audit = await auditService.getAuditById(auditId);
		const responseData = formatResponse({
			message: t({
				en: "Audit retrieved successfully",
				fr: "Audit récupéré avec succès",
				es: "Auditoría recuperada con éxito"
			}),
			description: t({
				en: "The audit has been retrieved successfully",
				fr: "L'audit a été récupéré avec succès",
				es: "La auditoría ha sido recuperada con éxito"
			}),
			data: audit.toJSON()
		});
		res.json(responseData);
		return;
	} catch (error) {
		ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};

//#endregion
export { createAudit, getAuditById, getAudits };
//# sourceMappingURL=audit.controller.mjs.map